package app

import (
	"database/sql"
	"fmt"
	"strconv"
	"strings"
	"time"

	"gitee.com/tomatomeatman/golang-repository/bricks/model/dbinfo"
	"gitee.com/tomatomeatman/golang-repository/bricks/model/emity"
	"gitee.com/tomatomeatman/golang-repository/bricks/model/globalconst"
	"gitee.com/tomatomeatman/golang-repository/bricks/model/globalvariable"
	"gitee.com/tomatomeatman/golang-repository/bricks/utils/function/data/integerutil"
	"gitee.com/tomatomeatman/golang-repository/bricks/utils/function/reflectutil"
	"gitee.com/tomatomeatman/golang-repository/bricks/utils/gorm"
	Log "github.com/cihub/seelog"
)

type CommonDao struct{}

/**
 * 新增
 * @param entity 待保存实体
 */
func (dao CommonDao) Add(entity dbinfo.Entity) *emity.MsgEmity {
	if entity.TableInfo().GbHasPid {
		return dao.AddNode(entity)
	}

	return dao.AddCommon(entity)
}

/**
 * 通用新增数据方法
 * @param entity 待保存实体
 */
func (dao CommonDao) AddCommon(entity dbinfo.Entity) *emity.MsgEmity {
	iRowsAffected, err := gorm.Add(entity)
	if err != nil {
		Log.Error("新增发生异常:", err)
		return emity.MsgEmity{}.Err(8041, "新增发生异常:", err)
	}

	if iRowsAffected < 1 {
		return emity.MsgEmity{}.Err(8042, "新增失败,影响数为0")
	}

	return emity.MsgEmity{}.Success(entity, "新增成功")
}

/**
 * 新增树节点
 * @param entity 检查用数据结构
 */
func (dao CommonDao) AddNode(entity dbinfo.Entity) *emity.MsgEmity {
	// var dataEntity interface{}
	// typeOf := reflect.TypeOf(entity)  //通过反射获取type定义
	// if typeOf.Kind() == reflect.Ptr { //是否指针类型
	// 	dataEntity = entity
	// } else if "reflect.Value" == typeOf.String() {
	// 	dataEntity = entity.(reflect.Value).Interface()
	// } else {
	// 	dataEntity = reflect.ValueOf(entity)
	// }

	tableInfo := entity.TableInfo() // entity.TableInfo()

	var build strings.Builder
	build.WriteString("INSERT INTO ")
	build.WriteString(gorm.GetDbName(tableInfo.GsDbName))
	build.WriteString(tableInfo.GsTableName)
	build.WriteString(" (@@@@@") //要替换'@@@@,'

	//未完
	// columns := dbinfo.TableInfo{}.GetColumnNames(entity)
	// for _, v := range columns {
	// 	if "/sPath/"
	// 	build.WriteString(v)

	// 	"CONCAT(IFNULL((select a.sPath from ${BricksBaseSystem}Department a where a.sId=IFNULL(#{sPid}, '00') ), '/00/'), #{sId}, '/') as sPath,"
	// }

	build.WriteString(" )")

	// params = append(params, sql.Named("iState", iState))

	// sMemo = strings.TrimSpace(sMemo)
	// if sMemo != "" {
	// 	build.WriteString(" ,sMemo=@sMemo")
	// 	params = append(params, sql.Named("sMemo", sMemo))
	// }

	// if 0 != iVersion {
	// 	build.WriteString(" ,iVersion=iVersion+1")
	// }

	dbResult := gorm.GetDB().Create(entity)
	if dbResult.Error != nil {
		Log.Error("新增发生异常:", dbResult.Error)
		return emity.MsgEmity{}.Err(8041, "新增发生异常:", dbResult.Error)
	}

	return emity.MsgEmity{}.Success(entity, "新增成功")
}

// 批量新增
func (dao CommonDao) Adds(entitys []dbinfo.Entity) *emity.MsgEmity {
	var me *emity.MsgEmity
	gorm.GetDB().Transaction(func(tx gorm.GormDB) error {
		for _, entity := range entitys {
			// var dataEntity interface{}
			// typeOf := reflect.TypeOf(entity)  //通过反射获取type定义
			// if typeOf.Kind() == reflect.Ptr { //是否指针类型
			// 	dataEntity = entity
			// } else if "reflect.Value" == typeOf.String() {
			// 	dataEntity = entity.(reflect.Value).Interface()
			// } else {
			// 	dataEntity = reflect.ValueOf(entity)
			// }

			if err := tx.Create(entity).Error; err != nil {
				Log.Error("批量新增发生异常:", err)
				me = emity.MsgEmity{}.Err(8041, "批量新增发生异常:", err)
				return err
			}
		}

		me = emity.MsgEmity{}.Success(entitys, "批量新增成功")
		return nil
	})

	return me
}

/**
 * 修改状态
 * @param entity 实体类
 * @param id 编号
 * @param iState 状态值
 * @param iVersion 记录版本号
 * @param sMemo 备注
 * @param unidirectional 是否单向 设置为单向则新值必须大于旧值才能执行
 * @return emity.MsgEmity 返回执行情况
 */
func (dao CommonDao) ChangeState(entity dbinfo.Entity, id interface{}, iState, iVersion int, sMemo string, unidirectional bool) *emity.MsgEmity {
	if fmt.Sprintf("%v", id) == "" {
		return emity.MsgEmity{}.Err(7001, "记录编号参数为空！")
	}

	tableInfo := entity.TableInfo()

	params := []interface{}{}
	params = append(params, sql.Named(tableInfo.GsKeyName+"Where", id))

	var build strings.Builder
	build.WriteString("UPDATE ")
	build.WriteString(gorm.GetDbName(tableInfo.GsDbName))
	build.WriteString(tableInfo.GsTableName)
	build.WriteString(" SET ")
	build.WriteString(globalconst.TableStateName)
	build.WriteString("=@")
	build.WriteString(globalconst.TableStateName)
	params = append(params, sql.Named(globalconst.TableStateName, iState))

	sMemo = strings.TrimSpace(sMemo)
	if sMemo != "" {
		build.WriteString(" ,")
		build.WriteString(globalconst.TablesMemo)
		build.WriteString("=@")
		build.WriteString(globalconst.TablesMemo)
		params = append(params, sql.Named(globalconst.TablesMemo, sMemo))
	}

	if iVersion != 0 {
		build.WriteString(" ,")
		build.WriteString(globalconst.TableVersionName)
		build.WriteString("= 1 + ")
		build.WriteString(globalconst.TableVersionName)
	}

	build.WriteString(" WHERE ")
	build.WriteString(tableInfo.GsKeyName)
	build.WriteString(" = @")
	build.WriteString(tableInfo.GsKeyName)
	build.WriteString("Where")
	if iVersion != 0 {
		build.WriteString(" AND ")
		build.WriteString(globalconst.TableVersionName)
		build.WriteString("=@iVersionWhere")
		params = append(params, sql.Named("iVersionWhere", iVersion))
	}

	if unidirectional {
		build.WriteString(" AND ")
		build.WriteString(globalconst.TableStateName)
		build.WriteString(" < @iStateWhere")
		params = append(params, sql.Named("iStateWhere", iState))
	}

	dbResult := gorm.Exec(build.String(), params)
	if dbResult.Error != nil {
		Log.Error("更新状态值发生异常:", dbResult.Error)
		return emity.MsgEmity{}.Err(7005, "更新状态值发生异常:", dbResult.Error)
	}

	if 0 < dbResult.RowsAffected {
		return emity.MsgEmity{}.Success(7999, "更新状态值成功！")
	}

	build.Reset()
	build.WriteString("SELECT ")
	build.WriteString(tableInfo.GsKeyName)
	build.WriteString(", ")
	build.WriteString(globalconst.TableStateName)

	if iVersion != 0 {
		build.WriteString(", ")
		build.WriteString(globalconst.TableVersionName)
	}

	build.WriteString(" FROM ")
	build.WriteString(gorm.GetDbName(tableInfo.GsDbName))
	build.WriteString(tableInfo.GsTableName)
	build.WriteString(" WHERE ")
	build.WriteString(tableInfo.GsKeyName)
	build.WriteString(" = @")
	build.WriteString(tableInfo.GsKeyName)

	var iStateOld, iVersionOld int
	row := gorm.Raw(build.String(), sql.Named(tableInfo.GsKeyName, id)).Row()
	row.Scan(&iStateOld, &iVersionOld)

	if iStateOld == 0 {
		return emity.MsgEmity{}.Err(7001, "没有找到对应数据！")
	}

	if (iVersion != 0) && (iVersion != iVersionOld) {
		return emity.MsgEmity{}.Err(7002, "更新状态值失败，系统中的数据可能已经被更新！")
	}

	if (iState >= 0) && (iState < iStateOld) {
		return emity.MsgEmity{}.Err(7003, "更新状态值失败，状态禁止逆操作！")
	}

	Log.Error("更新状态值未能得到预期影响值(预期1):", dbResult.RowsAffected)
	return emity.MsgEmity{}.Err(7004, "更新状态值未能得到预期影响值(预期1)", dbResult.RowsAffected)
}

/**
 * 修改步骤值(如果设置为单向则新值必须大于旧值)
 * @param id 编号
 * @param iSetp 步骤值
 * @param iVersion 记录版本号
 * @param sMemo 备注
 * @param unidirectional 是否单向 设置为单向则新值必须大于旧值才能执行
 * @param entity 实体类
 * @return emity.MsgEmity 返回执行情况
 */
func (dao CommonDao) ChangeSetp(entity dbinfo.Entity, id interface{}, iSetp, iVersion int, sMemo string, unidirectional bool) *emity.MsgEmity {
	if fmt.Sprintf("%v", id) == "" {
		return emity.MsgEmity{}.Err(7001, "记录编号参数为空！")
	}

	tableInfo := entity.TableInfo()

	params := []interface{}{}
	params = append(params, sql.Named(tableInfo.GsKeyName+"Where", id))

	var build strings.Builder
	build.WriteString("UPDATE ")
	build.WriteString(gorm.GetDbName(tableInfo.GsDbName))
	build.WriteString(tableInfo.GsTableName)
	build.WriteString(" SET iSetp=@iSetp")
	params = append(params, sql.Named("iSetp", iSetp))

	sMemo = strings.TrimSpace(sMemo)
	if sMemo != "" {
		build.WriteString(" ,")
		build.WriteString(globalconst.TablesMemo)
		build.WriteString("=@")
		build.WriteString(globalconst.TablesMemo)
		params = append(params, sql.Named(globalconst.TablesMemo, sMemo))
	}

	if iVersion != 0 {
		build.WriteString(" ,")
		build.WriteString(globalconst.TableVersionName)
		build.WriteString(" = 1 + ")
		build.WriteString(globalconst.TableVersionName)
	}

	build.WriteString(" WHERE ")
	build.WriteString(tableInfo.GsKeyName)
	build.WriteString(" = @")
	build.WriteString(tableInfo.GsKeyName)
	build.WriteString("Where")
	if iVersion != 0 {
		build.WriteString(" AND ")
		build.WriteString(globalconst.TableVersionName)
		build.WriteString(" =@iVersionWhere")
		params = append(params, sql.Named("iVersionWhere", iVersion))
	}

	if unidirectional {
		build.WriteString(" AND ")
		build.WriteString(globalconst.TableSetpName)
		build.WriteString(" < @iSetpWhere")
		params = append(params, sql.Named("iSetpWhere", iSetp))
	}

	if tableInfo.GbHasDelSign { //存在逻辑删除字段
		build.WriteString(" AND ")
		build.WriteString(globalconst.TableDelSignName)
		build.WriteString(" != 1")
	}

	dbResult := gorm.Exec(build.String(), params)
	if dbResult.Error != nil {
		Log.Error("更新步骤值发生异常:", dbResult.Error)
		return emity.MsgEmity{}.Err(7005, "更新步骤值发生异常:", dbResult.Error)
	}

	if 0 < dbResult.RowsAffected {
		return emity.MsgEmity{}.Success(7999, "更新步骤值成功！")
	}

	build.Reset()
	build.WriteString("SELECT ")
	build.WriteString(tableInfo.GsKeyName)
	build.WriteString(", ")
	build.WriteString(globalconst.TableSetpName)

	if iVersion != 0 {
		build.WriteString(", ")
		build.WriteString(globalconst.TableVersionName)
	}

	build.WriteString(" FROM ")
	build.WriteString(gorm.GetDbName(tableInfo.GsDbName))
	build.WriteString(tableInfo.GsTableName)
	build.WriteString(" WHERE ")
	build.WriteString(tableInfo.GsKeyName)
	build.WriteString(" = @")
	build.WriteString(tableInfo.GsKeyName)

	var iSetpOld, iVersionOld int
	row := gorm.Raw(build.String(), sql.Named(tableInfo.GsKeyName, id)).Row()
	row.Scan(&iSetpOld, &iVersionOld)

	if iSetpOld == 0 {
		return emity.MsgEmity{}.Err(7001, "没有找到对应数据！")
	}

	if (iVersion != 0) && (iVersion != iVersionOld) {
		return emity.MsgEmity{}.Err(7002, "更新步骤值失败，系统中的数据可能已经被更新！")
	}

	if (iSetp >= 0) && (iSetp < iSetpOld) {
		return emity.MsgEmity{}.Err(7003, "更新步骤值失败，状态禁止逆操作！")
	}

	Log.Error("更新步骤值未能得到预期影响值(预期1):", dbResult.RowsAffected)
	return emity.MsgEmity{}.Err(7004, "更新步骤值未能得到预期影响值(预期1)", dbResult.RowsAffected)
}

// 逻辑删除(非物理删除)
func (dao CommonDao) DelSign(entity dbinfo.Entity, id interface{}, iVersion int, currentUser string, onlyCreator bool) *emity.MsgEmity {
	if id == nil {
		return emity.MsgEmity{}.Err(7001, "记录编号为空")
	}

	tableInfo := entity.TableInfo()
	if !tableInfo.GbHasDelSign { //有逻辑删除字段标识才能进行逻辑删除
		return emity.MsgEmity{}.Err(1007, "没有逻辑删除字段,试图逻辑删除失败")
	}

	if tableInfo.GbHasVersion && (iVersion < 1) && (iVersion != integerutil.MaxInt()) {
		return emity.MsgEmity{}.Err(7002, "记录版本号不正确")
	}

	where := map[string]interface{}{}
	where[tableInfo.GsKeyName] = id

	var build strings.Builder
	build.WriteString("UPDATE ")
	build.WriteString(gorm.GetDbName(tableInfo.GsDbName))
	build.WriteString(tableInfo.GsTableName)
	build.WriteString(" SET ")
	build.WriteString(globalconst.TableDelSignName)
	build.WriteString(" = 1 WHERE ")
	build.WriteString(tableInfo.GsKeyName)
	build.WriteString(" = @")
	build.WriteString(tableInfo.GsKeyName)

	if tableInfo.GbHasVersion && (iVersion != integerutil.MaxInt()) {
		build.WriteString(" AND ")
		build.WriteString(globalconst.TableVersionName)
		build.WriteString("=@")
		build.WriteString(globalconst.TableVersionName)
		where[globalconst.TableVersionName] = iVersion
	}

	if onlyCreator && (currentUser != "") {
		build.WriteString(" AND ")
		build.WriteString(globalconst.TableCreatorName)
		build.WriteString("=@sCreator")
		where["sCreator"] = currentUser
	}

	dbResult := gorm.Exec(build.String(), where)

	if dbResult.Error != nil {
		Log.Error("逻辑删除发生异常:", dbResult.Error)
		return emity.MsgEmity{}.Err(1002, "逻辑删除发生异常:", dbResult.Error)
	}

	if dbResult.RowsAffected > 0 {
		return emity.MsgEmity{}.Success(1999, "(逻辑)删除成功")
	}

	//--影响数为0,需要进一步判断--//
	build.Reset()
	build.WriteString("SELECT ")
	build.WriteString(globalconst.TableDelSignName)
	build.WriteString(" FROM ")
	build.WriteString(gorm.GetDbName(tableInfo.GsDbName))
	build.WriteString(tableInfo.GsTableName)
	build.WriteString(" WHERE ")
	build.WriteString(tableInfo.GsKeyName)
	build.WriteString(" = ? ")

	var iCount int
	gorm.Raw(build.String(), id).Scan(&iCount)
	if iCount == 0 {
		return emity.MsgEmity{}.Success(1999, "没有发现此数据")
	}

	if !tableInfo.GbHasVersion {
		return emity.MsgEmity{}.Err(1003, "删除失败,数据还存在")
	}

	var oldVersion int
	var iDelSign int
	build.Reset()
	build.WriteString("SELECT ")
	build.WriteString(globalconst.TableVersionName)
	build.WriteString(", ")
	build.WriteString(globalconst.TableDelSignName)
	build.WriteString(" FROM ")
	build.WriteString(gorm.GetDbName(tableInfo.GsDbName))
	build.WriteString(tableInfo.GsTableName)
	build.WriteString(" WHERE ")
	build.WriteString(tableInfo.GsKeyName)
	build.WriteString(" = ?")
	gorm.Raw(build.String(), id).Row().Scan(&oldVersion, &iDelSign)

	if iDelSign == 1 {
		return emity.MsgEmity{}.Err(1004, "数据已经被(逻辑)删除")
	}

	if oldVersion == iVersion {
		return emity.MsgEmity{}.Err(1005, "删除失败,数据还存在")
	}

	return emity.MsgEmity{}.Err(1006, "(逻辑)删除失败,提供的版本号不正确,可能数据已经被改变")
}

// 逻辑删除(非物理删除)
func (dao CommonDao) DelSignByMap(entity dbinfo.Entity, whereInfo []dbinfo.WhereInfo, currentUser string, onlyCreator bool) *emity.MsgEmity {
	tableInfo := entity.TableInfo()
	if !tableInfo.GbHasDelSign { //有逻辑删除字段标识才能进行逻辑删除
		return emity.MsgEmity{}.Err(1007, "没有逻辑删除字段,试图逻辑删除失败")
	}

	var build strings.Builder
	build.WriteString("UPDATE ")
	build.WriteString(gorm.GetDbName(tableInfo.GsDbName))
	build.WriteString(tableInfo.GsTableName)
	build.WriteString(" SET ")
	build.WriteString(globalconst.TableDelSignName)
	build.WriteString(" = 1 WHERE 1=1")

	whereInfo = holdByEntityToWhereInfo(entity, whereInfo) //按实体保留条件
	where := map[string]interface{}{}
	for _, value := range whereInfo {
		condition := value.Condition
		if condition == "" {
			condition = "="
		}

		build.WriteString(" AND ")
		build.WriteString(value.Name)
		build.WriteString(" ")
		build.WriteString(condition)

		if value.ValueName != "" {
			build.WriteString(" ")
			build.WriteString(value.ValueName)
			continue
		}

		build.WriteString(" @")
		build.WriteString(value.Name)
		where[value.Name] = value.Value
	}

	if onlyCreator && (currentUser != "") {
		build.WriteString(" AND ")
		build.WriteString(globalconst.TableCreatorName)
		build.WriteString("=@sCreator")
		where["sCreator"] = currentUser
	}

	dbResult := gorm.Exec(build.String(), where)

	if dbResult.Error != nil {
		Log.Error("逻辑删除发生异常:", dbResult.Error)
		return emity.MsgEmity{}.Err(1002, "逻辑删除发生异常:", dbResult.Error)
	}

	if dbResult.RowsAffected > 0 {
		return emity.MsgEmity{}.Success(1999, "(逻辑)删除成功")
	}

	return emity.MsgEmity{}.Err(1003, "(逻辑)删除失败")
}

// 删除
func (dao CommonDao) Del(entity dbinfo.Entity, id interface{}, iVersion int, currentUser string, onlyCreator bool) *emity.MsgEmity {
	if id == nil {
		return emity.MsgEmity{}.Err(7001, "记录编号为空")
	}

	tableInfo := entity.TableInfo()

	if tableInfo.GbHasVersion && (iVersion < 1) && (iVersion != integerutil.MaxInt()) {
		return emity.MsgEmity{}.Err(7002, "记录版本号不正确")
	}

	where := map[string]interface{}{}
	where[tableInfo.GsKeyName] = id

	var build strings.Builder
	build.WriteString("DELETE FROM ")
	build.WriteString(gorm.GetDbName(tableInfo.GsDbName))
	build.WriteString(tableInfo.GsTableName)
	build.WriteString(" WHERE ")
	build.WriteString(tableInfo.GsKeyName)
	build.WriteString(" = @")
	build.WriteString(tableInfo.GsKeyName)

	if tableInfo.GbHasVersion && (iVersion != integerutil.MaxInt()) {
		build.WriteString(" AND ")
		build.WriteString(globalconst.TableVersionName)
		build.WriteString("=@")
		build.WriteString(globalconst.TableVersionName)
		where[globalconst.TableVersionName] = iVersion
	}

	if onlyCreator && (currentUser != "") {
		build.WriteString(" AND ")
		build.WriteString(globalconst.TableCreatorName)
		build.WriteString("=@sCreator")
		where["sCreator"] = currentUser
	}

	dbResult := gorm.Exec(build.String(), where)

	if dbResult.Error != nil {
		Log.Error("删除发生异常:", dbResult.Error)
		return emity.MsgEmity{}.Err(1002, "删除发生异常:", dbResult.Error)
	}

	if dbResult.RowsAffected > 0 {
		return emity.MsgEmity{}.Success(1999, "删除成功")
	}

	//--影响数为0,需要进一步判断--//
	build.Reset()
	build.WriteString("SELECT 1 FROM ")
	build.WriteString(gorm.GetDbName(tableInfo.GsDbName))
	build.WriteString(tableInfo.GsTableName)
	build.WriteString(" WHERE ")
	build.WriteString(tableInfo.GsKeyName)
	build.WriteString(" = ?")

	var iCount int
	gorm.Raw(build.String(), id).Scan(&iCount)
	if iCount == 0 {
		return emity.MsgEmity{}.Success(1999, "没有发现此数据")
	}

	if !tableInfo.GbHasVersion {
		return emity.MsgEmity{}.Err(1003, "删除失败,数据还存在")
	}

	var oldVersion int
	build.Reset()
	build.WriteString("SELECT ")
	build.WriteString(globalconst.TableVersionName)
	build.WriteString(" FROM ")
	build.WriteString(gorm.GetDbName(tableInfo.GsDbName))
	build.WriteString(tableInfo.GsTableName)
	build.WriteString(" WHERE ")
	build.WriteString(tableInfo.GsKeyName)
	build.WriteString(" = ?")
	gorm.Raw(build.String(), id).Scan(&oldVersion)

	if oldVersion == iVersion {
		return emity.MsgEmity{}.Err(1004, "删除失败,数据还存在")
	}

	return emity.MsgEmity{}.Err(1005, "删除失败,提供的版本号不正确,可能数据已经被改变")
}

// 删除
func (dao CommonDao) DelByMap(entity dbinfo.Entity, whereInfo []dbinfo.WhereInfo, currentUser string, onlyCreator bool) *emity.MsgEmity {
	if entity == nil {
		return emity.MsgEmity{}.Err(7001, "结构体参数为nil")
	}

	tableInfo := entity.TableInfo()

	var build strings.Builder
	build.WriteString("DELETE FROM ")
	build.WriteString(gorm.GetDbName(tableInfo.GsDbName))
	build.WriteString(tableInfo.GsTableName)
	build.WriteString(" WHERE 1=1")

	whereInfo = holdByEntityToWhereInfo(entity, whereInfo) //按实体保留条件

	where := map[string]interface{}{}
	for _, value := range whereInfo {
		condition := value.Condition
		if condition == "" {
			condition = "="
		}

		build.WriteString(" AND ")
		build.WriteString(value.Name)
		build.WriteString(" ")
		build.WriteString(condition)

		if value.ValueName != "" {
			build.WriteString(" ")
			build.WriteString(value.ValueName)
			continue
		}

		build.WriteString(" @")
		build.WriteString(value.Name)
		where[value.Name] = value.Value
	}

	if onlyCreator && (currentUser != "") {
		build.WriteString(" AND ")
		build.WriteString(globalconst.TableCreatorName)
		build.WriteString("=@sCreator")
		where["sCreator"] = currentUser
	}

	dbResult := gorm.Exec(build.String(), where)

	if dbResult.Error != nil {
		Log.Error("删除发生异常:", dbResult.Error)
		return emity.MsgEmity{}.Err(1002, "删除发生异常:", dbResult.Error)
	}

	return emity.MsgEmity{}.Success(1999, "删除成功")
}

/**
 * 修改
 * @param entity 对象类型
 * @param id 记录编号值
 * @param iVersion 记录版本号
 * @param data 待更新的字段和值
 * @param currentUser 当前用户
 * @param onlyCreator 仅创建用户
 * @return emity.MsgEmity
 */
func (dao CommonDao) Edit(entity dbinfo.Entity, id interface{}, iVersion int, data map[string]interface{}, currentUser string, onlyCreator bool) *emity.MsgEmity {
	if fmt.Sprintf("%v", id) == "" {
		return emity.MsgEmity{}.Err(7001, "记录编号参数为空！")
	}

	tableInfo := entity.TableInfo()
	params := []interface{}{} //[]sql.NamedArg{}
	params = append(params, sql.Named(tableInfo.GsKeyName, id))

	var build strings.Builder
	build.WriteString("UPDATE ")
	build.WriteString(gorm.GetDbName(tableInfo.GsDbName))
	build.WriteString(tableInfo.GsTableName)
	build.WriteString(" SET @@")

	for key, value := range data {
		build.WriteString(", ")
		build.WriteString(key)

		build.WriteString("=@")
		build.WriteString(key)
		params = append(params, sql.Named(key, value))
	}

	if tableInfo.GbHasVersion {
		build.WriteString(", ")
		build.WriteString(globalconst.TableVersionName)
		build.WriteString("= 1 + ")
		build.WriteString(globalconst.TableVersionName)
	}

	if tableInfo.GbHasModifieder {
		build.WriteString(",")
		build.WriteString(globalconst.TableModifiederName)
		build.WriteString("=@")
		build.WriteString(globalconst.TableModifiederName)
		params = append(params, sql.Named(globalconst.TableModifiederName, currentUser))
	}

	if tableInfo.GbHasModifiedDate {
		build.WriteString(", ")
		build.WriteString(globalconst.TableModifiedDateName)
		build.WriteString("=NOW()")
	}

	build.WriteString(" WHERE ")
	build.WriteString(tableInfo.GsKeyName)

	build.WriteString(" = @")
	build.WriteString(tableInfo.GsKeyName)

	if (iVersion != 0) && tableInfo.GbHasVersion {
		build.WriteString(" AND ")
		build.WriteString(globalconst.TableVersionName)
		build.WriteString("=@sCreator")
		params = append(params, sql.Named(globalconst.TableCreatorName, iVersion))
	}

	if onlyCreator && (currentUser != "") {
		build.WriteString(" AND ")
		build.WriteString(globalconst.TableCreatorName)
		build.WriteString("=@sCreator")
		params = append(params, sql.Named(globalconst.TableCreatorName, currentUser))
	}

	if tableInfo.GbHasDelSign { //存在逻辑删除字段
		build.WriteString(" AND ")
		build.WriteString(globalconst.TableDelSignName)
		build.WriteString(" != 1")
	}

	txt := strings.Replace(build.String(), " @@, ", " ", -1)
	dbResult := gorm.Exec(txt, params)
	if dbResult.Error != nil {
		Log.Error("更新数据发生异常:", dbResult.Error)
		return emity.MsgEmity{}.Err(7005, "更新数据发生异常:", dbResult.Error)
	}

	if 0 < dbResult.RowsAffected {
		return emity.MsgEmity{}.Success(7999, "更新数据成功！")
	}

	build.Reset()
	build.WriteString("SELECT ")
	build.WriteString(tableInfo.GsKeyName)

	if tableInfo.GbHasVersion {
		build.WriteString(", ")
		build.WriteString(globalconst.TableVersionName)
	}

	build.WriteString(" FROM ")
	build.WriteString(gorm.GetDbName(tableInfo.GsDbName))
	build.WriteString(tableInfo.GsTableName)
	build.WriteString(" WHERE ")
	build.WriteString(tableInfo.GsKeyName)
	build.WriteString(" = @")
	build.WriteString(tableInfo.GsKeyName)

	var vId, iVersionOld int
	row := gorm.Raw(build.String(), sql.Named(tableInfo.GsKeyName, id)).Row()
	row.Scan(&vId, &iVersionOld)

	if (fmt.Sprintf("%v", vId) == "") || (fmt.Sprintf("%v", vId) == "<nil>") {
		return emity.MsgEmity{}.Err(7001, "没有找到对应数据！")
	}

	if tableInfo.GbHasVersion && (iVersion != iVersionOld) {
		return emity.MsgEmity{}.Err(7002, "更新数据失败，系统中的数据可能已经被更新！")
	}

	Log.Error("更新数据未能得到预期影响值(预期1):", dbResult.RowsAffected)
	return emity.MsgEmity{}.Err(7004, "更新数据未能得到预期影响值(预期1)", dbResult.RowsAffected)
}

/**
 * 根据主键查询数据
 * @param entity 检查用数据结构
 * @param id 主键
 * @param currentUser 当前用户
 * @param onlyCreator 仅创建用户
 * @return emity.MsgEmity
 */
func (dao CommonDao) FindById(entity dbinfo.Entity, id interface{}, currentUser string, onlyCreator bool) *emity.MsgEmity {
	if id == nil {
		return emity.MsgEmity{}.Err(7001, "记录编号为空")
	}

	tableInfo := entity.TableInfo()

	where := map[string]interface{}{"id": id}

	var build strings.Builder
	build.WriteString("SELECT * FROM ")
	build.WriteString(gorm.GetDbName(tableInfo.GsDbName))
	build.WriteString(tableInfo.GsTableName)
	build.WriteString(" WHERE ")
	build.WriteString(tableInfo.GsKeyName)
	build.WriteString("=@id")

	if onlyCreator && (currentUser != "") {
		build.WriteString(" AND ")
		build.WriteString(globalconst.TableCreatorName)
		build.WriteString("=@sCreator")
		where["sCreator"] = currentUser
	}

	if tableInfo.GbHasDelSign { //存在逻辑删除字段
		build.WriteString(" AND ")
		build.WriteString(globalconst.TableDelSignName)
		build.WriteString(" != 1")
	}

	rows, err := gorm.Raw(build.String(), where).Rows()
	if err != nil {
		Log.Error("查询发生异常:", err)
		return emity.MsgEmity{}.Err(7002, "查询发生异常:", err)
	}
	defer rows.Close()

	res := gorm.ScanRows2mapI(rows)
	if res == nil {
		Log.Error("查询后数据转换发生异常:", err)
		return emity.MsgEmity{}.Err(7003, "查询后数据转换发生异常:", err)
	}

	if len(res) < 1 {
		return emity.MsgEmity{}.Err(7005, "查询成功,但没有数据")
	}

	return emity.MsgEmity{}.Success(res[0], "查询成功")
}

/**
 * 根据主键查询数据(返回结构体数据)
 * @param entity 检查用数据结构
 * @param id 主键
 * @param currentUser 当前用户
 * @param onlyCreator 仅创建用户
 * @return emity.MsgEmity
 */
func (dao CommonDao) EntityById(entity dbinfo.Entity, id interface{}, currentUser string, onlyCreator bool) *emity.MsgEmity {
	if id == nil {
		return emity.MsgEmity{}.Err(7001, "记录编号为空")
	}

	tableInfo := entity.TableInfo()

	where := map[string]interface{}{"id": id}

	var build strings.Builder
	build.WriteString("SELECT * FROM ")
	build.WriteString(gorm.GetDbName(tableInfo.GsDbName))
	build.WriteString(tableInfo.GsTableName)
	build.WriteString(" WHERE ")
	build.WriteString(tableInfo.GsKeyName)
	build.WriteString("=@id")

	if onlyCreator && (currentUser != "") {
		build.WriteString(" AND ")
		build.WriteString(globalconst.TableCreatorName)
		build.WriteString("=@sCreator")
		where["sCreator"] = currentUser
	}

	if tableInfo.GbHasDelSign { //存在逻辑删除字段
		build.WriteString(" AND ")
		build.WriteString(globalconst.TableDelSignName)
		build.WriteString(" != 1")
	}

	dbResult := gorm.Raw(build.String(), where).Scan(entity)
	if dbResult.Error != nil {
		Log.Error("查询发生异常:", dbResult.Error)
		return emity.MsgEmity{}.Err(7002, "查询发生异常")
	}

	if dbResult.RowsAffected != 1 {
		return emity.MsgEmity{}.Err(7003, "查询数据不符合")
	}

	return emity.MsgEmity{}.Success(entity, "查询成功")
}

func (dao CommonDao) EntityBySql(entityList interface{}, sql string, where map[string]interface{}) *emity.MsgEmity {
	sql = strings.TrimSpace(sql)
	if sql == "" {
		return emity.MsgEmity{}.Err(1001, "待执行语句为空")
	}

	if entityList == nil {
		return emity.MsgEmity{}.Err(1002, "结构体为空")
	}

	result, err := gorm.Query(sql, entityList, where)
	if err != nil {
		Log.Error("查询发生异常:", err)
		return emity.MsgEmity{}.Err(1003, "查询发生异常:", err)
	}

	return emity.MsgEmity{}.Success(result, "查询成功")
}

/**
 * 查询所有数据
 * @param entity 检查用数据结构
 * @param where 查询条件
 * @param currentUser 当前用户
 * @param onlyCreator 仅创建用户
 * @return emity.MsgEmity
 */
func (dao CommonDao) FindAll(entity dbinfo.Entity, whereInfo []dbinfo.WhereInfo, currentUser string, onlyCreator bool) *emity.MsgEmity {
	tableInfo := entity.TableInfo()

	var build strings.Builder
	build.WriteString("SELECT * FROM ")
	build.WriteString(gorm.GetDbName(tableInfo.GsDbName))
	build.WriteString(tableInfo.GsTableName)

	whereInfo = holdByEntityToWhereInfo(entity, whereInfo) //按实体保留
	where := map[string]interface{}{}
	if len(whereInfo) > 0 {
		build.WriteString(" WHERE 1=1")
		for _, value := range whereInfo {
			condition := value.Condition
			if condition == "" {
				condition = "="
			}

			build.WriteString(" AND ")
			build.WriteString(value.Name)
			build.WriteString(" ")
			build.WriteString(condition)

			if value.ValueName != "" {
				build.WriteString(" ")
				build.WriteString(value.ValueName)
				continue
			}

			build.WriteString(" @")
			build.WriteString(value.Name)
			where[value.Name] = value.Value
		}
	}

	if onlyCreator && (currentUser != "") {
		where[globalconst.TableCreatorName] = currentUser
	}

	if tableInfo.GbHasDelSign { //存在逻辑删除字段
		build.WriteString(" AND ")
		build.WriteString(globalconst.TableDelSignName)
		build.WriteString(" != 1")
	}

	text := strings.Replace(build.String(), "1=1 AND ", "", -1)

	rows, err := gorm.Raw(text, where).Rows()
	if err != nil {
		Log.Error("查询发生异常:", err)
		return emity.MsgEmity{}.Err(1005, "查询发生异常:", err)
	}
	defer rows.Close()

	res := gorm.ScanRows2mapI(rows)
	if res == nil {
		return emity.MsgEmity{}.Err(1006, "查询后数据转换发生异常")
	}

	return emity.MsgEmity{}.Success(res, "查询成功")
}

/**
 * 查询指定时间内数据
 * @param entity 检查用数据结构
 * @param sDateSt 开始时间
 * @param sDateEd 结束时间
 * @param currentUser 当前用户
 * @param onlyCreator 仅创建用户
 * @return emity.MsgEmity
 */
func (dao CommonDao) FindByDate(entity dbinfo.Entity, sDateSt string, sDateEd string, currentUser string, onlyCreator bool) *emity.MsgEmity {
	var dDateSt time.Time
	if sDateSt == "" {
		d, _ := time.ParseDuration("-168h") //7天前
		dDateSt = time.Now().Add(d)
	} else {
		temp, err := time.ParseInLocation("2006-01-02 15:04:05", sDateSt, time.Local)
		if err != nil {
			return emity.MsgEmity{}.Err(7001, "'开始时间'格式不符合要求,推荐使用格式:'YYYY-MM-DD HH:mm:ss'")
		}

		dDateSt = temp
	}

	var dDateEd time.Time
	if sDateEd == "" {
		dDateEd = time.Now()
	} else {
		temp, err := time.ParseInLocation("2006-01-02 15:04:05", sDateSt, time.Local)
		if err != nil {
			return emity.MsgEmity{}.Err(7002, "'结束时间'格式不符合要求,推荐使用格式:'YYYY-MM-DD HH:mm:ss'")
		}

		dDateEd = temp
	}

	tableInfo := entity.TableInfo()

	var build strings.Builder
	build.WriteString("SELECT * FROM ")
	build.WriteString(gorm.GetDbName(tableInfo.GsDbName))
	build.WriteString(tableInfo.GsTableName)
	build.WriteString(" WHERE ")
	build.WriteString(globalconst.TableCreateDateName)
	build.WriteString(" BETWEEN @dDateSt AND @dDateEd")

	where := map[string]interface{}{
		"dDateSt": dDateSt,
		"dDateEd": dDateEd,
	}

	if onlyCreator && (currentUser != "") {
		build.WriteString(" AND ")
		build.WriteString(globalconst.TableCreatorName)
		build.WriteString("=@sCreator")
		where["sCreator"] = currentUser
	}

	if tableInfo.GbHasDelSign { //存在逻辑删除字段
		build.WriteString(" AND ")
		build.WriteString(globalconst.TableDelSignName)
		build.WriteString(" != 1")
	}

	rows, err := gorm.Raw(build.String(), where).Rows()
	if err != nil {
		Log.Error("查询发生异常:", err)
		return emity.MsgEmity{}.Err(7003, "查询发生异常:", err)
	}
	defer rows.Close()

	res := gorm.ScanRows2mapI(rows)
	if res == nil {
		return emity.MsgEmity{}.Err(7004, "查询后数据转换发生异常")
	}

	return emity.MsgEmity{}.Success(res, "查询成功")
}

/**
 * 查询指定行数据
 * @param entity 检查用数据结构
 * @param id 记录编号
 * @param currentUser 当前用户
 * @param onlyCreator 仅创建用户
 * @return emity.MsgEmity
 */
func (dao CommonDao) FindByRow(entity dbinfo.Entity, id interface{}, currentUser string, onlyCreator bool) *emity.MsgEmity {
	if id == nil {
		return emity.MsgEmity{}.Err(7001, "记录编号为空")
	}

	sId := fmt.Sprintf("%v", id)
	if sId == "" {
		return emity.MsgEmity{}.Err(7002, "记录编号为空")
	}

	tableInfo := entity.TableInfo()

	// var s reflect.Type
	// typeOf := reflect.TypeOf(entity)  //通过反射获取type定义
	// if typeOf.Kind() == reflect.Ptr { //是否指针类型
	// 	s = reflect.TypeOf(entity).Elem() //通过反射获取type定义
	// } else {
	// 	s = typeOf //通过反射获取type定义
	// }

	var appendFieldSql strings.Builder
	var dictionarySql strings.Builder
	var oTherJoin = map[string]string{}

	var build strings.Builder
	build.WriteString("SELECT ")
	build.WriteString(tableInfo.GsTableName)
	build.WriteString(".*,")

	//for i := 0; i < s.NumField(); i++ {
	for _, dataInfo := range entity.AllDataInfo(entity) {
		f, d := ModuleUtil{}.GetFindByPageSelectSqlByField(dataInfo, tableInfo.GsTableName, dataInfo.GsName, oTherJoin)
		if f != "" {
			appendFieldSql.WriteString(f)
		}

		if d != "" {
			dictionarySql.WriteString(d)
		}
	}

	build.WriteString(appendFieldSql.String())
	build.WriteString(" FROM ")
	build.WriteString(gorm.GetDbName(tableInfo.GsDbName))
	build.WriteString(tableInfo.GsTableName)
	build.WriteString(" AS ")
	build.WriteString(tableInfo.GsTableName)

	if dictionarySql.String() != "" {
		build.WriteString(dictionarySql.String())
	}

	build.WriteString(" WHERE ")
	build.WriteString(tableInfo.GsKeyName)
	build.WriteString(" =@")
	build.WriteString(tableInfo.GsKeyName)

	where := map[string]interface{}{tableInfo.GsKeyName: id}
	if onlyCreator && (currentUser != "") {
		build.WriteString(" AND ")
		build.WriteString(globalconst.TableCreatorName)
		build.WriteString("=@sCreator")
		where["sCreator"] = currentUser
	}

	if tableInfo.GbHasDelSign { //存在逻辑删除字段
		build.WriteString(" AND ")
		build.WriteString(globalconst.TableDelSignName)
		build.WriteString(" != 1")
	}

	text := strings.Replace(build.String(), ", FROM ", " FROM ", -1)

	rows, err := gorm.Raw(text, where).Rows()
	if err != nil {
		Log.Error("查询发生异常:", err)
		return emity.MsgEmity{}.Err(1005, "查询发生异常:", err)
	}
	defer rows.Close()

	res := gorm.ScanRows2mapI(rows)
	if res == nil {
		return emity.MsgEmity{}.Err(1006, "查询后数据转换发生异常")
	}

	if len(res) < 1 {
		return emity.MsgEmity{}.Success(res, "查询成功,但没有数据")
	}

	return emity.MsgEmity{}.Success(res[0], "查询成功")
}

/**
 * 查询分页数据
 * @param entity 检查用数据结构
 * @param findByPageParam 分页参数
 * @param currentUser 当前用户
 * @param onlyCreator 仅创建用户
 * @return emity.MsgEmity
 */
func (dao CommonDao) FindByPage(entity dbinfo.Entity, findByPageParam dbinfo.FindByPageParam, currentUser string, onlyCreator bool) *emity.MsgEmity {
	findByPageCountSql, findByPageSql, params := ModuleUtil{}.GetFindByPageSelectSql(currentUser, entity, findByPageParam, onlyCreator)

	var iCount int
	dbResult := gorm.Raw(findByPageCountSql, params).Find(&iCount)

	// var dbResult *ggorm.DB
	// if len(params) < 1 {
	// 	dbResult = gorm.Raw(findByPageCountSql).Find(&iCount)
	// } else {
	// 	dbResult = gorm.Raw(findByPageCountSql, params).Find(&iCount)
	// }

	if dbResult.Error != nil {
		Log.Error("查询分页数量发生异常:", dbResult.Error)
		return emity.MsgEmity{}.Err(7001, "查询分页数量发生异常:", dbResult.Error)
	}

	if iCount < 1 {
		res := make([]map[string]interface{}, 0)
		page := findByPageParam.Gpage
		page.GiCountRow = 0
		page.SetRecord(res)

		return emity.MsgEmity{}.Success(page, "查询分页数量成功但没有数据")
	}

	rows, err := gorm.Raw(findByPageSql, params).Rows()
	if err != nil {
		Log.Error("查询分页数量发生异常:", err)
		return emity.MsgEmity{}.Err(7002, "查询分页数量发生异常")
	}
	defer rows.Close()

	page := findByPageParam.Gpage
	page.GiCountRow = iCount

	iCountPage := (iCount / page.GiSize)
	if (iCount % page.GiSize) > 0 {
		iCountPage = iCountPage + 1
	}
	page.GiCountPage = iCountPage

	res := gorm.ScanRows2mapI(rows)

	if res == nil {
		return emity.MsgEmity{}.Err(7003, "查询分页数量成功但解析数据发生异常")
	}

	page.SetRecord(res)

	return emity.MsgEmity{}.Success(page, "查询分页数量成功")
}

// func (dao CommonDao) FindData(OrderInfoList orders, String sLikeStr, Object condition,
// 			onlyCreator bool, entity dbinfo.Entity) {

// 			}

// 取路径字段
func (dao CommonDao) GetPath(sId, dbName, tableName string) string {
	var build strings.Builder
	build.WriteString("SELECT sPath FROM ")
	build.WriteString(dbName)
	build.WriteString(tableName)
	build.WriteString(" WHERE ")
	build.WriteString(globalconst.TableMajorKeyString)
	build.WriteString("=?")

	var sPath string
	dbResult := gorm.Raw(build.String(), sId).Scan(&sPath)
	if dbResult.Error != nil {
		Log.Error("查询路径信息发生异常:", dbResult.Error)
		return "/00/"
	}

	return sPath
}

/**
 * 取指定节点下的子节点编号
 * @param tableInfo 表信息
 * @param sPid 父节点
 * @return
 */
func (dao CommonDao) NewChildId(tableInfo *dbinfo.TableInfo, sPid string) *emity.MsgEmity {
	var build strings.Builder
	build.WriteString("SELECT (cur + 1) AS newId FROM (")
	build.WriteString(" 		select cast(A.${globalconst.TableMajorKeyString} AS SIGNED) AS cur, IFNULL(")
	build.WriteString(" 			(select MIN( CAST(B.${globalconst.TableMajorKeyString} as signed integer)) from ${sDbName}${sTableName} AS B")
	build.WriteString(" 				where cast(B.${globalconst.TableMajorKeyString} AS SIGNED) > cast(A.${globalconst.TableMajorKeyString} AS SIGNED)")
	build.WriteString(" 				and B.${globalconst.TablePidKey} = #{sPid}")
	build.WriteString(" 				and CAST(B.${globalconst.TableMajorKeyString} as signed integer) != 0")                                                              // 过滤字段中含非数字的记录
	build.WriteString(" 				and CAST(B.${globalconst.TableMajorKeyString} as signed integer) = CAST(B.${globalconst.TableMajorKeyString} as signed integer) +0") // 过滤字段中含非数字的记录
	build.WriteString(" 			), 99999999) AS nxt")
	build.WriteString(" 		from ${sDbName}${sTableName} AS A")
	build.WriteString(" 		where A.${globalconst.TablePidKey} = #{sPid}")
	build.WriteString(" 		and CAST(A.${globalconst.TableMajorKeyString} as signed integer) != 0")                                                              // 过滤字段中含非数字的记录
	build.WriteString(" 		and CAST(A.${globalconst.TableMajorKeyString} as signed integer) = CAST(A.${globalconst.TableMajorKeyString} as signed integer) +0") // 过滤字段中含非数字的记录
	build.WriteString(" 	) AS D")
	build.WriteString(" WHERE (nxt - cur > 1) or (nxt = 99999999)")
	build.WriteString(" ORDER BY cur")
	build.WriteString(" LIMIT 0, 1")

	txt := build.String()
	txt = strings.Replace(txt, "${sDbName}", gorm.GetDbName(tableInfo.GsDbName), -1)
	txt = strings.Replace(txt, "${sTableName}", tableInfo.GsTableName, -1)
	txt = strings.Replace(txt, "${globalconst.TablePidKey}", globalconst.TablePidKey, -1)
	txt = strings.Replace(txt, "${globalconst.TableMajorKeyString}", globalconst.TableMajorKeyString, -1)
	txt = strings.Replace(txt, "#{sPid}", "@sPid", -1)

	newId := ""
	dbResult := gorm.Raw(txt, sql.Named(globalconst.TablePidKey, sPid)).Find(&newId)
	if dbResult.Error != nil {
		Log.Error("查询发生异常:", dbResult.Error)
		return emity.MsgEmity{}.Err(1001, "查询数据发生异常:", dbResult.Error)
	}

	return emity.MsgEmity{}.Success(newId, "获取子节点编号成功")
}

/**
 * 验证新增数据是否存在重复
 * @param dbEntity 数据实体
 * @param currentUser 当前用户
 * @return emity.MsgEmity
 */
func (dao CommonDao) ValidEntityRepeatByAdd(dbEntity dbinfo.Entity, currentUser string) *emity.MsgEmity {
	tableInfo := dbEntity.TableInfo()
	customService := globalvariable.Get(tableInfo.GsTableName + "_ModuleService")

	//-- 树形结构 --//
	if tableInfo.GbHasPid {
		if nil == customService { //如果没有自定义业务层
			return dao.CommonCheckRepeatByAddAndTree(dbEntity, currentUser) //通用树型结构表添加数据时重复检查方法
		}

		method := reflectutil.GetMethod(customService, "CheckRepeatByAddAndTree")
		if !method.IsValid() { //如果自定义业务层定义了自检方法
			return dao.CommonCheckRepeatByAddAndTree(dbEntity, currentUser) //通用树型结构表添加数据时重复检查方法
		}

		result := reflectutil.DoMethod(customService, "CheckRepeatByAddAndTree", dbEntity)
		me := result[0].Interface()
		return me.(*emity.MsgEmity)
	}

	//--不是树形数据则使用普通方法检查--//
	if nil == customService { //如果没有自定义业务层
		return dao.CommonCheckRepeatByAdd(dbEntity, currentUser) //通用添加数据时重复检查方法
	}

	method := reflectutil.GetMethod(customService, "CheckRepeatByAdd")
	if !method.IsValid() { //如果自定义业务层定义了自检方法
		return dao.CommonCheckRepeatByAdd(dbEntity, currentUser) //通用添加数据时重复检查方法
	}

	result := reflectutil.DoMethod(customService, "CheckRepeatByAdd", dbEntity)
	me := result[0].Interface()
	return me.(*emity.MsgEmity)
}

/**
 * 验证更新数据是否存在重复
 * @param dbEntity 数据实体
 * @param id 主键
 * @param data 数据
 * @param currentUser 当前用户
 * @return emity.MsgEmity
 */
func (dao CommonDao) ValidEntityRepeatByEdit(entity dbinfo.Entity, id interface{}, data map[string]interface{}, currentUser string) *emity.MsgEmity {
	tableInfo := entity.TableInfo()
	customService := globalvariable.Get(tableInfo.GsTableName + "_ModuleService")

	//-- 树形结构 --//
	if tableInfo.GbHasPid {
		if nil == customService { //如果没有自定义业务层
			return dao.CommonCheckRepeatByEditAndTree(entity, id, data["sName"], currentUser) //通用树型结构表添加数据时重复检查方法
		}

		method := reflectutil.GetMethod(customService, "CheckRepeatByEditAndTree")
		if !method.IsValid() { //如果自定义业务层定义了自检方法
			return dao.CommonCheckRepeatByEditAndTree(entity, id, data["sName"], currentUser) //通用树型结构表添加数据时重复检查方法
		}

		result := reflectutil.DoMethod(customService, "CheckRepeatByEditAndTree", id, data["sName"])
		me := result[0].Interface()
		return me.(*emity.MsgEmity)
	}

	//--不是树形数据则使用普通方法检查--//
	if nil == customService { //如果没有自定义业务层
		return dao.CommonCheckRepeatByEdit(entity, id, currentUser) //通用添加数据时重复检查方法
	}

	method := reflectutil.GetMethod(customService, "CheckRepeatByEdit")
	if !method.IsValid() { //如果自定义业务层定义了自检方法
		return dao.CommonCheckRepeatByEdit(entity, id, currentUser) //通用添加数据时重复检查方法
	}

	result := reflectutil.DoMethod(customService, "CheckRepeatByEdit", data, id)
	me := result[0].Interface()
	return me.(*emity.MsgEmity)
}

/**
 * 通用树型结构表添加数据时重复检查方法
 * @param dbEntity 数据实体
 * @param currentUser 当前用户
 * @return emity.MsgEmity
 */
func (dao CommonDao) CommonCheckRepeatByAddAndTree(dbEntity dbinfo.Entity, currentUser string) *emity.MsgEmity {
	vName := reflectutil.GetFieldValue(dbEntity, globalconst.GtableTreeNodeName)
	if nil == vName {
		return emity.MsgEmity{}.Err(1001, "节点名称为空")
	}

	tableInfo := dbEntity.TableInfo()

	sName := vName.(string)

	var sPid string
	vPid := reflectutil.GetFieldValue(dbEntity, globalconst.GtablePidKey)
	if nil != vPid {
		sPid = vPid.(string)
	} else {
		sPid = globalconst.TableTreeRootValue
	}

	if sPid == "" {
		sPid = globalconst.TableTreeRootValue
	}

	//同一层节点下,展现名不能相同//
	var build strings.Builder
	build.WriteString("SELECT SUM(iCount) AS iCount FROM (")
	build.WriteString(" 	select count(1) as iCount from ${sDbName}${sTableName}")
	build.WriteString(" 	where ${globalconst.TablePidKey} = #{sPid} and ${globalconst.TableTreeNodeName} = #{sName}")
	build.WriteString(") TMP")

	txt := build.String()
	txt = strings.Replace(txt, "${sDbName}", gorm.GetDbName(tableInfo.GsDbName), -1)
	txt = strings.Replace(txt, "${sTableName}", tableInfo.GsTableName, -1)
	txt = strings.Replace(txt, "${globalconst.TablePidKey}", globalconst.TablePidKey, -1)
	txt = strings.Replace(txt, "${globalconst.TableTreeNodeName}", globalconst.TableTreeNodeName, -1)
	txt = strings.Replace(txt, "#{sPid}", "@sPid", -1)
	txt = strings.Replace(txt, "#{sName}", "@sName", -1)

	var iCount int
	dbResult := gorm.Raw(txt, sql.Named(globalconst.TablePidKey, sPid), sql.Named("sName", sName)).Find(&iCount)
	if dbResult.Error != nil {
		Log.Error("查询发生异常:", dbResult.Error)
		return emity.MsgEmity{}.Err(1002, "查询数据发生异常:", dbResult.Error)
	}

	if iCount != 0 {
		return emity.MsgEmity{}.Err(1003, "节点重复")
	}

	return emity.MsgEmity{}.Success(1999, "节点未重复")
}

/**
 * 通用树型结构表添加数据时重复检查方法
 * @param dbEntity 数据实体
 * @param id 主键
 * @param sName 展现名
 * @param currentUser 当前用户
 * @return emity.MsgEmity
 */
func (dao CommonDao) CommonCheckRepeatByEditAndTree(entity dbinfo.Entity, id interface{}, sName interface{}, currentUser string) *emity.MsgEmity {
	if (sName == nil) || (sName == "") || (sName == "<nil>") {
		return emity.MsgEmity{}.Err(1001, "节点名称为空")
	}

	tableInfo := entity.TableInfo()

	//同一层节点下,展现名不能相同//
	var build strings.Builder
	build.WriteString("SELECT SUM(iCount) AS iCount FROM (")
	build.WriteString(" 	select count(1) as iCount from ${sDbName}${sTableName}")
	build.WriteString(" 	where ${sId} <> @sId")
	build.WriteString(" 	and ${globalconst.TablePidKey} = (select a.${globalconst.TablePidKey} from ${sDbName}${sTableName} a where a.${sId} = #{sId})")
	build.WriteString(" 	and ${globalconst.TableTreeNodeName} = #{sName}")
	build.WriteString(") TMP")

	txt := build.String()
	txt = strings.Replace(txt, "${sDbName}", gorm.GetDbName(tableInfo.GsDbName), -1)
	txt = strings.Replace(txt, "${sTableName}", tableInfo.GsTableName, -1)
	txt = strings.Replace(txt, "${sId}", tableInfo.GsKeyName, -1)
	txt = strings.Replace(txt, "${globalconst.TablePidKey}", globalconst.TablePidKey, -1)
	txt = strings.Replace(txt, "${globalconst.TableTreeNodeName}", globalconst.TableTreeNodeName, -1)
	txt = strings.Replace(txt, "#{sName}", "@sName", -1)

	var iCount int
	dbResult := gorm.Raw(txt, sql.Named(tableInfo.GsKeyName, id), sql.Named("sName", sName)).Find(&iCount)
	if dbResult.Error != nil {
		Log.Error("查询发生异常:", dbResult.Error)
		return emity.MsgEmity{}.Err(1002, "查询数据发生异常:", dbResult.Error)
	}

	if iCount != 0 {
		return emity.MsgEmity{}.Err(1003, "节点重复")
	}

	return emity.MsgEmity{}.Success(1999, "节点未重复")
}

/**
 * 通用添加数据时重复检查方法
 * @param dbEntity 数据实体
 * @param currentUser 当前用户
 * @return emity.MsgEmity
 */
func (dao CommonDao) CommonCheckRepeatByAdd(dbEntity dbinfo.Entity, currentUser string) *emity.MsgEmity {
	tableInfo := dbEntity.TableInfo()

	vCheckRepeatCombination := globalvariable.Get(tableInfo.GsTableName + "_CheckRepeatCombination")
	vCheckRepeatAlone := globalvariable.Get(tableInfo.GsTableName + "_CheckRepeatAlone")

	k := 0

	//检查待新增内容是否存在重复数据(多字段组合重复即重复)集合
	if (vCheckRepeatCombination != nil) && (len(vCheckRepeatCombination.([]string)) > 0) {
		checkRepeatCombination := vCheckRepeatCombination.([]string)

		var build strings.Builder
		build.WriteString("SELECT COUNT(1) AS iCount FROM ${sDbName}${sTableName} WHERE 1=1")

		var temp strings.Builder
		temp.WriteString("[")

		where := make(map[string]interface{})
		for _, value := range checkRepeatCombination {
			build.WriteString(" AND ")
			build.WriteString(value)
			build.WriteString(" = @")
			build.WriteString(value)

			where[value] = reflectutil.GetFieldValue(dbEntity, value)

			dataInfo := dbEntity.GetDataInfo(value)
			temp.WriteString("、'")
			temp.WriteString(dataInfo.GsComment)
			temp.WriteString("'")
		}

		if tableInfo.GbHasDelSign { //存在逻辑删除字段
			build.WriteString(" AND ")
			build.WriteString(globalconst.TableDelSignName)
			build.WriteString(" != 1")
		}

		txt := strings.Replace(build.String(), "1=1 AND ", "", -1)
		txt = strings.Replace(txt, "${sDbName}", gorm.GetDbName(tableInfo.GsDbName), -1)
		txt = strings.Replace(txt, "${sTableName}", tableInfo.GsTableName, -1)

		iCount := 0
		dbResult := gorm.Raw(txt, where).Find(&iCount)
		if dbResult.Error != nil {
			Log.Error("验证数据是否重复发生异常:", dbResult.Error)
			return emity.MsgEmity{}.Err(1001, "验证数据是否重复发生异常:", dbResult.Error)
		}

		if iCount != 0 {
			temp.WriteString("]组合发现数据重复")
			return emity.MsgEmity{}.Err(1002, strings.Replace(temp.String(), "、", "", 1))
		}

		k++
	}

	//检查待新增内容是否存在重复数据(单独字段重复即重复)集合
	if (vCheckRepeatAlone != nil) && (len(vCheckRepeatAlone.(map[string]int)) > 0) {
		checkRepeatAlone := vCheckRepeatAlone.(map[string]int)

		var build strings.Builder
		build.WriteString("SELECT SUM(iCount) FROM (")

		where := make(map[string]interface{})
		for key, value := range checkRepeatAlone {
			build.WriteString(" union all select (SIGN(COUNT(1)) * ")
			build.WriteString(strconv.Itoa(value))
			build.WriteString(") as iCount ")
			build.WriteString(" from ${sDbName}${sTableName} ")
			build.WriteString(" where ")
			build.WriteString(key)
			build.WriteString("= @")
			build.WriteString(key)

			if tableInfo.GbHasDelSign { //存在逻辑删除字段
				build.WriteString(" and ")
				build.WriteString(globalconst.TableDelSignName)
				build.WriteString(" != 1")
			}

			where[key] = reflectutil.GetFieldValue(dbEntity, key)
		}

		build.WriteString(") TMP")

		txt := strings.Replace(build.String(), " union all ", " ", 1)
		txt = strings.Replace(txt, "${sDbName}", gorm.GetDbName(tableInfo.GsDbName), -1)
		txt = strings.Replace(txt, "${sTableName}", tableInfo.GsTableName, -1)

		iCount := 0
		dbResult := gorm.Raw(txt, where).Find(&iCount)
		if dbResult.Error != nil {
			Log.Error("验证数据是否重复发生异常:", dbResult.Error)
			return emity.MsgEmity{}.Err(1003, "验证数据是否重复发生异常:", dbResult.Error)
		}

		if iCount != 0 {
			var temp strings.Builder
			str := fmt.Sprintf("%0*d", len(checkRepeatAlone), iCount)
			array := []rune(str)

			for key, value := range checkRepeatAlone {
				i := len(strconv.Itoa(value))
				if array[i] != 0 {
					continue
				}

				dataInfo := dbEntity.GetDataInfo(key)
				temp.WriteString("、'")
				temp.WriteString(dataInfo.GsComment)
				temp.WriteString("'")
			}

			temp.WriteString("存在重复")

			return emity.MsgEmity{}.Err(1004, strings.Replace(temp.String(), "、", "", 1))
		}

		k++
	}

	if k == 0 {
		return emity.MsgEmity{}.Success("没有设定验证函数,通过")
	}

	return emity.MsgEmity{}.Success("经验证,通过")
}

/**
 * 通用更新数据时重复检查方法
 * @param entity 数据实体
 * @param id 数据主键
 * @param currentUser 当前用户
 * @return emity.MsgEmity
 */
func (dao CommonDao) CommonCheckRepeatByEdit(entity dbinfo.Entity, id interface{}, currentUser string) *emity.MsgEmity {
	tableInfo := entity.TableInfo()

	vCheckRepeatCombination := globalvariable.Get(tableInfo.GsTableName + "_CheckRepeatCombination")
	vCheckRepeatAlone := globalvariable.Get(tableInfo.GsTableName + "_CheckRepeatAlone")

	k := 0

	//检查待新增内容是否存在重复数据(多字段组合重复即重复)集合
	if (vCheckRepeatCombination != nil) && (len(vCheckRepeatCombination.([]string)) > 0) {
		checkRepeatCombination := vCheckRepeatCombination.([]string)

		var build strings.Builder
		build.WriteString("SELECT COUNT(1) AS iCount FROM ${sDbName}${sTableName} WHERE 1=1")

		var temp strings.Builder
		temp.WriteString("[")

		where := make(map[string]interface{})
		where[tableInfo.GsKeyName] = id
		build.WriteString(" AND ")
		build.WriteString(tableInfo.GsKeyName)
		build.WriteString(" != @")
		build.WriteString(tableInfo.GsKeyName)

		for _, value := range checkRepeatCombination {
			build.WriteString(" AND ")
			build.WriteString(value)
			build.WriteString(" = @")
			build.WriteString(value)

			where[value] = reflectutil.GetFieldValue(entity, value) //利用反射取属性值

			dataInfo := entity.GetDataInfo(value)
			temp.WriteString("、'")
			temp.WriteString(dataInfo.GsComment)
			temp.WriteString("'")
		}

		if tableInfo.GbHasDelSign { //存在逻辑删除字段
			build.WriteString(" AND ")
			build.WriteString(globalconst.TableDelSignName)
			build.WriteString(" != 1")
		}

		txt := strings.Replace(build.String(), "1=1 AND ", "", -1)
		txt = strings.Replace(txt, "${sDbName}", gorm.GetDbName(tableInfo.GsDbName), -1)
		txt = strings.Replace(txt, "${sTableName}", tableInfo.GsTableName, -1)

		iCount := 0
		dbResult := gorm.Raw(txt, where).Find(&iCount)
		if dbResult.Error != nil {
			Log.Error("验证数据是否重复发生异常:", dbResult.Error)
			return emity.MsgEmity{}.Err(1001, "验证数据是否重复发生异常:", dbResult.Error)
		}

		if iCount != 0 {
			temp.WriteString("]组合发现数据重复")
			return emity.MsgEmity{}.Err(1002, strings.Replace(temp.String(), "、", "", 1))
		}

		k++
	}

	//检查待新增内容是否存在重复数据(单独字段重复即重复)集合
	if (vCheckRepeatAlone != nil) && (len(vCheckRepeatAlone.(map[string]int)) > 0) {
		checkRepeatAlone := vCheckRepeatAlone.(map[string]int)

		var build strings.Builder
		build.WriteString("SELECT SUM(iCount) FROM (")

		where := make(map[string]interface{})
		where[tableInfo.GsKeyName] = id

		for key, value := range checkRepeatAlone {
			build.WriteString(" union all select (SIGN(COUNT(1)) * ")
			build.WriteString(strconv.Itoa(value))
			build.WriteString(") as iCount ")
			build.WriteString(" from ${sDbName}${sTableName} ")
			build.WriteString(" where ")
			build.WriteString(key)
			build.WriteString("= @")
			build.WriteString(key)
			build.WriteString(" and ")
			build.WriteString(tableInfo.GsKeyName)
			build.WriteString(" != @")
			build.WriteString(tableInfo.GsKeyName)

			if tableInfo.GbHasDelSign { //存在逻辑删除字段
				build.WriteString(" and ")
				build.WriteString(globalconst.TableDelSignName)
				build.WriteString(" != 1")
			}

			where[key] = reflectutil.GetFieldValue(entity, key)
		}

		build.WriteString(") TMP")

		txt := strings.Replace(build.String(), " union all ", " ", 1)
		txt = strings.Replace(txt, "${sDbName}", gorm.GetDbName(tableInfo.GsDbName), -1)
		txt = strings.Replace(txt, "${sTableName}", tableInfo.GsTableName, -1)

		iCount := 0
		dbResult := gorm.Raw(txt, where).Find(&iCount)
		if dbResult.Error != nil {
			Log.Error("验证数据是否重复发生异常:", dbResult.Error)
			return emity.MsgEmity{}.Err(1003, "验证数据是否重复发生异常:", dbResult.Error)
		}

		if iCount != 0 {
			var temp strings.Builder
			str := fmt.Sprintf("%0*d", len(checkRepeatAlone), iCount)
			array := []rune(str)

			for key, value := range checkRepeatAlone {
				i := len(strconv.Itoa(value))
				if array[i] != 0 {
					continue
				}

				dataInfo := entity.GetDataInfo(key)
				temp.WriteString("、'")
				temp.WriteString(dataInfo.GsComment)
				temp.WriteString("'")
			}

			temp.WriteString("存在重复")

			return emity.MsgEmity{}.Err(1004, strings.Replace(temp.String(), "、", "", 1))
		}

		k++
	}

	if k == 0 {
		return emity.MsgEmity{}.Success("没有设定验证函数,通过")
	}

	return emity.MsgEmity{}.Success("经验证,通过")
}

/**
 * 读取树形结构数据
 * @param entity 数据实体
 * @param sGroupColumn 分组字段
 * @param sGroupName 分组名称
 * @param currentUser 当前用户
 * @return emity.MsgEmity
 */
func (dao CommonDao) FindByTree(entity dbinfo.Entity, sGroupColumn, sGroupName, currentUser string) *emity.MsgEmity {
	if !entity.HasColumnNames(entity, sGroupName) {
		return emity.MsgEmity{}.Err(1001, "指定分组字段不存在！")
	}

	tableInfo := entity.TableInfo()

	var build strings.Builder
	build.WriteString("SELECT * FROM ")
	build.WriteString(gorm.GetDbName(tableInfo.GsDbName))
	build.WriteString(tableInfo.GsTableName)
	build.WriteString(" WHERE ")
	build.WriteString(globalconst.TableMajorKeyString)
	build.WriteString(" > 0")

	where := make(map[string]interface{})
	if sGroupName != "" {
		build.WriteString(" AND ")
		build.WriteString(globalconst.TablePathKey)
		build.WriteString(" LIKE (")
		build.WriteString(" 	select CONCAT(a.")
		build.WriteString(globalconst.TablePathKey)
		build.WriteString(", '%')")
		build.WriteString(" 	from ${sDbName}${sTableName} a")

		if sGroupColumn != "" {
			build.WriteString(" 	where a.")
			build.WriteString(sGroupColumn) //指定字段作为分组标识
			build.WriteString(" = ?")
		} else if tableInfo.GbHasOnlyign {
			build.WriteString(" 	where a.")                 //启用唯一标识作为关键字
			build.WriteString(globalconst.TableOnlyignName) //启用唯一标识作为关键字
			build.WriteString(" = @sGroupName")             //启用唯一标识作为关键字
		} else {
			build.WriteString(" 	where a.")
			build.WriteString(globalconst.TableTreeNodeName)
			build.WriteString(" = @sGroupName")
		}

		build.WriteString(" )")
		where["sGroupName"] = sGroupName
	}

	build.WriteString(" ORDER BY ")
	build.WriteString(globalconst.TablePathKey)

	rows, err := gorm.Raw(build.String(), where).Rows()
	if err != nil {
		Log.Error("查询发生异常:", err)
		return emity.MsgEmity{}.Err(1002, "查询发生异常:", err)
	}
	defer rows.Close()

	res := gorm.ScanRows2mapI(rows)
	if res == nil {
		return emity.MsgEmity{}.Err(1003, "查询后数据转换发生异常")
	}

	return emity.MsgEmity{}.Success(res, "查询成功")
}

/**
 * 根据字段名取指定记录编号的数据库表中对应字段的值
 * @param entity 实体类
 * @param id 记录编号
 * @param fieldNames 待取数据的字段名称集合
 * @param currentUser 当前用户
 * @Param onlyCreator 是否只取当前用户创建的数据
 * @return emity.MsgEmity 返回内容data中存放的是Map
 */
func (dao CommonDao) GetValueByFieldName(entity dbinfo.Entity, id interface{}, fieldNames []string, currentUser string, onlyCreator bool) *emity.MsgEmity {
	fieldNames = holdByEntityToArray(entity, fieldNames) //按实体保留数组中的数据
	if len(fieldNames) < 1 {
		return emity.MsgEmity{}.Err(7001, "没有对应的数据可查询！")
	}

	tableInfo := entity.TableInfo()

	var build strings.Builder
	build.WriteString("SELECT ")

	for _, val := range fieldNames {
		build.WriteString(",")
		build.WriteString(val)
	}

	build.WriteString(" FROM ")
	build.WriteString(gorm.GetDbName(tableInfo.GsDbName))
	build.WriteString(tableInfo.GsTableName)
	build.WriteString(" WHERE ")
	build.WriteString(tableInfo.GsKeyName)
	build.WriteString("=@")
	build.WriteString(tableInfo.GsKeyName)

	if tableInfo.GbHasDelSign { //存在逻辑删除字段
		build.WriteString(" AND ")
		build.WriteString(globalconst.TableDelSignName)
		build.WriteString(" != 1")
	}

	where := make(map[string]interface{})
	where[tableInfo.GsKeyName] = id

	if onlyCreator && (currentUser != "") {
		build.WriteString(" AND ")
		build.WriteString(globalconst.TableCreatorName)
		build.WriteString("=@sCreator")
		where["sCreator"] = currentUser
	}

	sql := strings.Replace(build.String(), ",", "", 1)
	rows, err := gorm.Raw(sql, where).Rows()
	if err != nil {
		Log.Error("查询发生异常:", err)
		return emity.MsgEmity{}.Err(7002, "查询发生异常:", err)
	}
	defer rows.Close()

	res := gorm.ScanRows2mapI(rows)
	if res == nil {
		Log.Error("查询后数据转换发生异常:", err)
		return emity.MsgEmity{}.Err(7003, "查询后数据转换发生异常:", err)
	}

	if len(res) < 1 {
		return emity.MsgEmity{}.Err(7004, "数据不存在！")
	}

	return emity.MsgEmity{}.Success(res[0], "查询成功")
}

/**
 * 根据字段名取指定记录编号的数据库表中对应字段的值
 * @param entity 实体类
 * @param id 记录编号
 * @param fieldName 待取数据的字段名称集合
 * @param currentUser 当前用户
 * @Param onlyCreator 是否只取当前用户创建的数据
 * @return emity.MsgEmity 返回内容data中存放的是Map
 */
func (dao CommonDao) GetValueByField(entity dbinfo.Entity, id interface{}, fieldName, currentUser string, onlyCreator bool) *emity.MsgEmity {
	fieldName = strings.TrimSpace(fieldName)
	if fieldName == "" {
		return emity.MsgEmity{}.Err(7001, "没有对应的数据可查询！")
	}

	columns := strings.Split(fieldName, ",")
	columns = holdByEntityToArray(entity, columns)
	if len(columns) < 1 {
		return emity.MsgEmity{}.Err(7002, "没有对应的字段数据可查询！")
	}

	fieldName = ""
	for _, val := range columns {
		temp := strings.TrimSpace(val)
		if temp == "" {
			continue
		}

		fieldName = fieldName + "," + temp
	}

	if fieldName == "" {
		return emity.MsgEmity{}.Err(7003, "没有对应的字段数据可查询！")
	}

	fieldName = fieldName[1:]

	tableInfo := entity.TableInfo()

	var build strings.Builder
	build.WriteString("SELECT ")
	build.WriteString(fieldName)
	build.WriteString(" FROM ")
	build.WriteString(gorm.GetDbName(tableInfo.GsDbName))
	build.WriteString(tableInfo.GsTableName)
	build.WriteString(" WHERE ")
	build.WriteString(tableInfo.GsKeyName)
	build.WriteString(" = @")
	build.WriteString(tableInfo.GsKeyName)

	if tableInfo.GbHasDelSign { //存在逻辑删除字段
		build.WriteString(" AND ")
		build.WriteString(globalconst.TableDelSignName)
		build.WriteString(" != 1")
	}

	where := make(map[string]interface{})
	where[tableInfo.GsKeyName] = id

	if onlyCreator && (currentUser != "") {
		build.WriteString(" AND ")
		build.WriteString(globalconst.TableCreatorName)
		build.WriteString("=@sCreator")
		where["sCreator"] = currentUser
	}

	sql := strings.Replace(build.String(), ",", "", 1)
	rows, err := gorm.Raw(sql, where).Rows()
	if err != nil {
		Log.Error("查询发生异常:", err)
		return emity.MsgEmity{}.Err(7003, "查询发生异常:", err)
	}
	defer rows.Close()

	res := gorm.ScanRows2mapI(rows)
	if res == nil {
		Log.Error("查询后数据转换发生异常:", err)
		return emity.MsgEmity{}.Err(7004, "查询后数据转换发生异常:", err)
	}

	if len(res) < 1 {
		return emity.MsgEmity{}.Err(7005, "数据不存在！")
	}

	return emity.MsgEmity{}.Success(res[0], "查询成功")
}

/**
 * 根据字段名取指定条件的数据库表中对应字段的值
 * @param entity 实体类
 * @param whereInfo 条件
 * @param fieldName 待取数据的字段名称集合
 * @param currentUser 当前用户
 * @Param onlyCreator 是否只取当前用户创建的数据
 * @return emity.MsgEmity 返回内容data中存放的是Map
 */
func (dao CommonDao) GetValueByWhere(entity dbinfo.Entity, whereInfo []dbinfo.WhereInfo, fieldName, currentUser string, onlyCreator bool) *emity.MsgEmity {
	fieldName = strings.TrimSpace(fieldName)
	if fieldName == "" {
		return emity.MsgEmity{}.Err(7001, "没有对应的数据可查询！")
	}

	if !entity.HasColumnNames(entity, fieldName) {
		return emity.MsgEmity{}.Err(7002, "指定字段不存在！")
	}

	tableInfo := entity.TableInfo()

	var build strings.Builder
	build.WriteString("SELECT ")
	build.WriteString(fieldName)
	build.WriteString(" FROM ")
	build.WriteString(gorm.GetDbName(tableInfo.GsDbName))
	build.WriteString(tableInfo.GsTableName)
	build.WriteString(" WHERE 1=1")

	where := make(map[string]interface{})
	for _, value := range whereInfo {
		condition := value.Condition
		if condition == "" {
			condition = "="
		}

		build.WriteString(" AND ")
		build.WriteString(value.Name)
		build.WriteString(" ")
		build.WriteString(condition)

		if value.ValueName != "" {
			build.WriteString(" ")
			build.WriteString(value.ValueName)
			continue
		}

		build.WriteString(" @")
		build.WriteString(value.Name)
		where[value.Name] = value.Value
	}

	if onlyCreator && (currentUser != "") {
		build.WriteString(" AND ")
		build.WriteString(globalconst.TableCreatorName)
		build.WriteString("=@sCreator")
		where["sCreator"] = currentUser
	}

	sql := strings.Replace(build.String(), ",", "", 1)
	sql = strings.Replace(sql, " 1=1 AND ", " ", -1)
	sql = strings.Replace(sql, " WHERE 1=1", " ", -1)
	rows, err := gorm.Raw(sql, where).Rows()
	if nil != err {
		Log.Error("查询发生异常:", err)
		return emity.MsgEmity{}.Err(7003, "查询发生异常:", err)
	}
	defer rows.Close()

	res := gorm.ScanRows2mapI(rows)
	if res == nil {
		Log.Error("查询发生异常:", err)
		return emity.MsgEmity{}.Err(7004, "查询发生异常:", err)
	}

	if len(res) < 1 {
		return emity.MsgEmity{}.Err(7005, "数据不存在！")
	}

	return emity.MsgEmity{}.Success(res, "查询成功")
}

/**
 * 取记录对应的版本号
 * @param entity 实体类
 * @param idName 编号
 * @return
 */
func (dao CommonDao) GetiVersion(entity dbinfo.Entity, id interface{}) *emity.MsgEmity {
	if fmt.Sprintf("%v", id) == "" {
		return emity.MsgEmity{}.Err(7001, "记录编号参数为空！")
	}

	tableInfo := entity.TableInfo()

	var build strings.Builder
	build.WriteString("SELECT ")
	build.WriteString(globalconst.TableVersionName)
	build.WriteString(" FROM ")
	build.WriteString(gorm.GetDbName(tableInfo.GsDbName))
	build.WriteString(tableInfo.GsTableName)
	build.WriteString(" WHERE ")
	build.WriteString(tableInfo.GsKeyName)
	build.WriteString("=@")
	build.WriteString(tableInfo.GsKeyName)

	if tableInfo.GbHasDelSign { //存在逻辑删除字段
		build.WriteString(" AND ")
		build.WriteString(globalconst.TableDelSignName)
		build.WriteString(" != 1")
	}

	where := make(map[string]interface{})
	where[tableInfo.GsKeyName] = id

	iVersion := 0
	dbResult := gorm.Raw(build.String(), where).Find(&iVersion)
	if dbResult.Error != nil {
		Log.Error("验证数据是否重复发生异常:", dbResult.Error)
		return emity.MsgEmity{}.Err(7002, "验证数据是否重复发生异常:", dbResult.Error)
	}

	if iVersion == 0 {
		return emity.MsgEmity{}.Err(7003, "没有发现此数据")
	}

	return emity.MsgEmity{}.Success(iVersion, "查询成功")
}

/**
 * 取记录对应的状态值
 * @param entity 实体类
 * @param id 编号
 * @return
 */
func (dao CommonDao) GetiState(entity dbinfo.Entity, id interface{}) *emity.MsgEmity {
	if fmt.Sprintf("%v", id) == "" {
		return emity.MsgEmity{}.Err(7001, "记录编号参数为空！")
	}

	tableInfo := entity.TableInfo()

	var build strings.Builder
	build.WriteString("SELECT ")
	build.WriteString(globalconst.TableStateName)
	build.WriteString(" FROM ")
	build.WriteString(gorm.GetDbName(tableInfo.GsDbName))
	build.WriteString(tableInfo.GsTableName)
	build.WriteString(" WHERE ")
	build.WriteString(tableInfo.GsKeyName)
	build.WriteString("=@")
	build.WriteString(tableInfo.GsKeyName)

	if tableInfo.GbHasDelSign { //存在逻辑删除字段
		build.WriteString(" AND ")
		build.WriteString(globalconst.TableDelSignName)
		build.WriteString(" != 1")
	}

	where := make(map[string]interface{})
	where[tableInfo.GsKeyName] = id

	iState := 0
	dbResult := gorm.Raw(build.String(), where).Find(&iState)
	if dbResult.Error != nil {
		Log.Error("验证数据是否重复发生异常:", dbResult.Error)
		return emity.MsgEmity{}.Err(7002, "验证数据是否重复发生异常:", dbResult.Error)
	}

	if iState == 0 {
		return emity.MsgEmity{}.Err(7003, "没有发现此数据")
	}

	return emity.MsgEmity{}.Success(iState, "查询成功")
}

/**
 * 根据关键值取对象集合
 * @Param entity 实体类
 * @Param where 存放查询条件
 * @Param currentUser 当前用户
 * @Param onlyCreator 是否只取当前用户创建的数据
 * @return emity.MsgEmity
 */
func (dao CommonDao) FindByKey(entity dbinfo.Entity, whereInfo []dbinfo.WhereInfo, currentUser string, onlyCreator bool) *emity.MsgEmity {
	whereInfo = holdByEntityToWhereInfo(entity, whereInfo) //按实体保留条件
	if len(whereInfo) < 1 {
		return emity.MsgEmity{}.Err(7002, "没有对应的查询条件！")
	}

	tableInfo := entity.TableInfo()

	var build strings.Builder
	build.WriteString("SELECT * FROM ")
	build.WriteString(gorm.GetDbName(tableInfo.GsDbName))
	build.WriteString(tableInfo.GsTableName)
	build.WriteString(" WHERE 1=1")

	where := map[string]interface{}{}
	for _, value := range whereInfo {
		condition := value.Condition
		if condition == "" {
			condition = "="
		}

		build.WriteString(" AND ")
		build.WriteString(value.Name)
		build.WriteString(" ")
		build.WriteString(condition)

		if value.ValueName != "" {
			build.WriteString(" ")
			build.WriteString(value.ValueName)
			continue
		}

		build.WriteString(" @")
		build.WriteString(value.Name)
		where[value.Name] = value.Value
	}

	if onlyCreator && (currentUser != "") {
		build.WriteString(" AND ")
		build.WriteString(globalconst.TableCreatorName)
		build.WriteString("=@sCreator")
		where["sCreator"] = currentUser
	}

	if tableInfo.GbHasDelSign { //存在逻辑删除字段
		build.WriteString(" AND ")
		build.WriteString(globalconst.TableDelSignName)
		build.WriteString(" != 1")
	}

	sql := strings.Replace(build.String(), " 1=1 AND ", " ", 1)
	sql = strings.Replace(sql, " WHERE 1=1", " ", -1)
	rows, iCode, err := gorm.FindToMap(sql, where)
	if err != nil {
		return emity.MsgEmity{}.Err(iCode, err.Error())
	}

	return emity.MsgEmity{}.Success(rows, "查询成功")
}

/**
 * 根据关键值取对象集合中的第一个
 * @Param entity 实体类
 * @Param whereInfo 存放查询条件
 * @Param currentUser 当前用户
 * @param onlyCreator 是否只取当前用户创建的数据
 * @param fields 指定要查询的字段集合
 * @return emity.MsgEmity
 */
func (dao CommonDao) FindOneByKey(entity dbinfo.Entity, whereInfo []dbinfo.WhereInfo, currentUser string, onlyCreator bool, fields ...string) *emity.MsgEmity {
	columns := "," + entity.BaseColumnNames() + ","
	whereInfoTemp := []dbinfo.WhereInfo{}
	for _, val := range whereInfo {
		if !strings.Contains(columns, ","+val.Name+",") {
			continue
		}

		whereInfoTemp = append(whereInfoTemp, val)
	}

	if len(whereInfoTemp) < 1 {
		return emity.MsgEmity{}.Err(7001, "没有对应的查询条件！")
	}

	tableInfo := entity.TableInfo()

	var build strings.Builder
	build.WriteString("SELECT ")

	fields = holdByEntityToArray(entity, fields) //按实体保留数组中的数据
	if len(fields) < 1 {
		return emity.MsgEmity{}.Err(7002, "没有对应的字段数据可查询！")
	}

	for _, val := range fields {
		build.WriteString(",")
		build.WriteString(val)
	}

	build.WriteString(" FROM ")
	build.WriteString(gorm.GetDbName(tableInfo.GsDbName))
	build.WriteString(tableInfo.GsTableName)
	build.WriteString(" WHERE 1=1")

	where := map[string]interface{}{}
	for _, value := range whereInfoTemp {
		condition := value.Condition
		if condition == "" {
			condition = "="
		}

		build.WriteString(" AND ")
		build.WriteString(value.Name)
		build.WriteString(" ")
		build.WriteString(condition)

		if value.ValueName != "" {
			build.WriteString(" ")
			build.WriteString(value.ValueName)
			continue
		}

		build.WriteString(" @")
		build.WriteString(value.Name)
		where[value.Name] = value.Value
	}

	if onlyCreator && (currentUser != "") {
		build.WriteString(" AND ")
		build.WriteString(globalconst.TableCreatorName)
		build.WriteString("=@sCreator")
		where["sCreator"] = currentUser
	}

	if tableInfo.GbHasDelSign { //存在逻辑删除字段
		build.WriteString(" AND ")
		build.WriteString(globalconst.TableDelSignName)
		build.WriteString(" != 1")
	}

	text := strings.Replace(build.String(), "SELECT ,", "SELECT ", -1)
	text = strings.Replace(text, " 1=1 AND ", " ", -1)
	text = strings.Replace(text, " WHERE 1=1", " ", -1)
	data, iCode, err := gorm.FindToMap(text, where)
	if err != nil {
		return emity.MsgEmity{}.Err(iCode, err)
	}

	if iCode < 1 {
		return emity.MsgEmity{}.Err(7004, "数据不存在！")
	}

	return emity.MsgEmity{}.Success(data[0], "查询成功")
}

/**
 * 根据关键值取对象集合中的符合条件的第一条记录的指定字段
 * @Param entity 实体类
 * @Param where 存放查询条件
 * @param fieldName 指定要查询的字段
 * @param currentUser 当前用户
 * @param onlyCreator 仅查询创建者
 * @return emity.MsgEmity
 */
func (dao CommonDao) FindValueByKey(entity dbinfo.Entity, whereInfo []dbinfo.WhereInfo, fieldName, currentUser string, onlyCreator bool) *emity.MsgEmity {
	whereInfo = holdByEntityToWhereInfo(entity, whereInfo) //按实体保留条件
	if len(whereInfo) < 1 {
		return emity.MsgEmity{}.Err(7002, "没有对应的查询条件！")
	}

	fieldName = strings.TrimSpace(fieldName)
	if fieldName == "" {
		return emity.MsgEmity{}.Err(7002, "没有待查字段！")
	}

	if !entity.HasColumnNames(entity, fieldName) {
		return emity.MsgEmity{}.Err(7003, "指定字段不存在！")
	}

	tableInfo := entity.TableInfo()

	var build strings.Builder
	build.WriteString("SELECT ")
	build.WriteString(fieldName)
	build.WriteString(" FROM ")
	build.WriteString(gorm.GetDbName(tableInfo.GsDbName))
	build.WriteString(tableInfo.GsTableName)
	build.WriteString(" WHERE 1=1")

	where := map[string]interface{}{}
	for _, value := range whereInfo {
		condition := value.Condition
		if condition == "" {
			condition = "="
		}

		build.WriteString(" AND ")
		build.WriteString(value.Name)
		build.WriteString(" ")
		build.WriteString(condition)

		if value.ValueName != "" {
			build.WriteString(" ")
			build.WriteString(value.ValueName)
			continue
		}

		build.WriteString(" @")
		build.WriteString(value.Name)
		where[value.Name] = value.Value
	}

	if onlyCreator && (currentUser != "") {
		build.WriteString(" AND ")
		build.WriteString(globalconst.TableCreatorName)
		build.WriteString("=@sCreator")
		where["sCreator"] = currentUser
	}

	if tableInfo.GbHasDelSign { //存在逻辑删除字段
		build.WriteString(" AND ")
		build.WriteString(globalconst.TableDelSignName)
		build.WriteString(" != 1")
	}

	text := strings.Replace(build.String(), " 1=1 AND ", " ", -1)
	text = strings.Replace(text, " WHERE 1=1", " ", -1) //没有条件
	rows, iCount, err := gorm.FindToMap(text, where)
	if err != nil {
		return emity.MsgEmity{}.Err(iCount, err.Error())
	}

	if iCount < 1 {
		return emity.MsgEmity{}.Err(7006, "数据不存在！")
	}

	val := rows[0][fieldName]
	
	return emity.MsgEmity{}.Success(val, "查询成功")
}

/**
 * 根据关键值取对象集合中的符合条件的第一条记录的指定字段
 * @Param entity 实体类
 * @Param where 存放查询条件
 * @param fieldMap 指定要查询的字段集合(原字段, 别名)
 * @param currentUser 当前用户
 * @param onlyCreator 仅查询创建者
 * @return emity.MsgEmity
 */
func (dao CommonDao) FindByFields(entity dbinfo.Entity, whereInfo []dbinfo.WhereInfo, fieldMap map[string]string, currentUser string, onlyCreator bool) *emity.MsgEmity {
	whereInfo = holdByEntityToWhereInfo(entity, whereInfo) //按实体保留条件
	if len(whereInfo) < 1 {
		return emity.MsgEmity{}.Err(7001, "没有对应的查询条件！")
	}

	var columns strings.Builder
	columns.WriteString("@@@")
	var orderStr strings.Builder
	orderStr.WriteString("@@@")

	iCount := 0
	for k, v := range fieldMap {
		if !entity.HasColumnNames(entity, k) {
			continue
		}

		iCount++

		columns.WriteString(",")
		columns.WriteString(k)

		orderStr.WriteString(",")
		orderStr.WriteString(k)

		if v != "" {
			columns.WriteString(" AS ")
			columns.WriteString(v)
		}
	}

	if iCount < 1 {
		return emity.MsgEmity{}.Err(7003, "没有符合的字段！")
	}

	tableInfo := entity.TableInfo()

	var build strings.Builder
	build.WriteString("SELECT ")
	build.WriteString(strings.Replace(columns.String(), "@@@,", "", -1))
	build.WriteString(" FROM ")
	build.WriteString(gorm.GetDbName(tableInfo.GsDbName))
	build.WriteString(tableInfo.GsTableName)
	build.WriteString(" WHERE 1=1")

	where := map[string]interface{}{}
	for _, value := range whereInfo {
		condition := value.Condition
		if condition == "" {
			condition = "="
		}

		build.WriteString(" AND ")
		build.WriteString(value.Name)
		build.WriteString(" ")
		build.WriteString(condition)

		if value.ValueName != "" {
			build.WriteString(" ")
			build.WriteString(value.ValueName)
			continue
		}

		build.WriteString(" @")
		build.WriteString(value.Name)
		where[value.Name] = value.Value
	}

	if onlyCreator && (currentUser != "") {
		build.WriteString(" AND ")
		build.WriteString(globalconst.TableCreatorName)
		build.WriteString("=@sCreator")
		where["sCreator"] = currentUser
	}

	if tableInfo.GbHasDelSign { //存在逻辑删除字段
		build.WriteString(" AND ")
		build.WriteString(globalconst.TableDelSignName)
		build.WriteString(" != 1")
	}

	build.WriteString(" ORDER BY ")
	build.WriteString(strings.Replace(orderStr.String(), "@@@,", "", -1))

	text := strings.Replace(build.String(), " WHERE 1=1 AND ", " WHERE ", -1)
	text = strings.Replace(text, " WHERE 1=1", " ", -1)

	rows, err := gorm.Raw(text, where).Rows()
	if err != nil {
		Log.Error("查询发生异常:", err)
		return emity.MsgEmity{}.Err(7004, "查询发生异常:", err)
	}
	defer rows.Close()

	res := gorm.ScanRows2mapI(rows)
	if res == nil {
		Log.Error("查询后数据转换发生异常:", err)
		return emity.MsgEmity{}.Err(7005, "查询后数据转换发生异常:", err)
	}

	if len(res) < 1 {
		return emity.MsgEmity{}.Err(7006, "数据不存在！")
	}

	return emity.MsgEmity{}.Success(res, "查询成功")
}

/**
 * 根据关键值查数量
 * @Param entity 实体类
 * @Param where 存放查询条件
 * @param currentUser 当前用户
 * @param onlyCreator 仅查询创建者
 * @return emity.MsgEmity
 */
func (dao CommonDao) FindCountByKey(entity dbinfo.Entity, whereInfo []dbinfo.WhereInfo, currentUser string, onlyCreator bool) *emity.MsgEmity {
	whereInfo = holdByEntityToWhereInfo(entity, whereInfo) //按实体保留条件
	if len(whereInfo) < 1 {
		return emity.MsgEmity{}.Err(7001, "没有对应的查询条件！")
	}

	tableInfo := entity.TableInfo()

	var build strings.Builder
	build.WriteString("SELECT COUNT(1) AS iCount FROM ")
	build.WriteString(gorm.GetDbName(tableInfo.GsDbName))
	build.WriteString(tableInfo.GsTableName)
	build.WriteString(" WHERE 1=1")

	where := map[string]interface{}{}
	for _, value := range whereInfo {
		condition := value.Condition
		if condition == "" {
			condition = "="
		}

		build.WriteString(" AND ")
		build.WriteString(value.Name)
		build.WriteString(" ")
		build.WriteString(condition)

		if value.ValueName != "" {
			build.WriteString(" ")
			build.WriteString(value.ValueName)
			continue
		}

		build.WriteString(" @")
		build.WriteString(value.Name)
		where[value.Name] = value.Value
	}

	if onlyCreator && (currentUser != "") {
		build.WriteString(" AND ")
		build.WriteString(globalconst.TableCreatorName)
		build.WriteString("=@sCreator")
		where["sCreator"] = currentUser
	}

	if tableInfo.GbHasDelSign { //存在逻辑删除字段
		build.WriteString(" AND ")
		build.WriteString(globalconst.TableDelSignName)
		build.WriteString(" != 1")
	}

	sql := strings.Replace(build.String(), " 1=1 AND ", " ", 1)
	sql = strings.Replace(sql, " WHERE 1=1", " ", -1)

	rows, err := gorm.Raw(sql, where).Rows()
	if err != nil {
		Log.Error("查询发生异常:", err)
		return emity.MsgEmity{}.Err(7002, "查询发生异常:", err)
	}
	defer rows.Close()

	res := gorm.ScanRows2mapI(rows)
	if res == nil {
		Log.Error("查询后数据转换发生异常:", err)
		return emity.MsgEmity{}.Err(7003, "查询后数据转换发生异常:", err)
	}

	if len(res) < 1 {
		return emity.MsgEmity{}.Err(7004, "数据不存在！")
	}

	return emity.MsgEmity{}.Success(res[0]["iCount"], "查询成功")
}

/**
 * 以事务方式执行多个sql
 * 注意:Mapper必须存在才能执行
 * @param sqls [sql, params]
 * @return emity.MsgEmity 一个执行失败则回滚
 */
func (dao CommonDao) TransactionSql(sqls map[string]map[string]interface{}) *emity.MsgEmity {
	if len(sqls) < 1 {
		return emity.MsgEmity{}.Err(7001, "没有需要执行的sql")
	}

	tx := gorm.GetDB().Begin() // 开始事务

	for sql, params := range sqls {
		if err := tx.Exec(sql, params).Error; err == nil {
			continue
		}

		Log.Error("sql执行失败:", sql)
		tx.Rollback() //回滚事务
		return emity.MsgEmity{}.Err(7002, "没有需要执行的sql")
	}

	tx.Commit() //提交事务

	return emity.MsgEmity{}.Success(7999, "事务执行成功")
}

/**
 * 根据字段名取分组数据
 * @param entity 实体类
 * @param sCreator 指定用户
 * @param fields 字段名与别名对象
 * @param currentUser 当前用户
 * @param onlyCreator 用户查询限制(仅创建者可见)
 * @return
 */
func (dao CommonDao) GroupByField(entity dbinfo.Entity, sCreator string, fields map[string]string, currentUser string, onlyCreator bool) *emity.MsgEmity {
	return dao.GroupByFieldBase(entity, sCreator, fields, currentUser, onlyCreator, false)
}

/**
 * 根据字段名取分组数据,并返回数量
 * @param entity 实体类
 * @param sCreator 指定用户
 * @param fields 字段名与别名对象
 * @param currentUser 当前用户
 * @param onlyCreator 用户查询限制(仅创建者可见)
 * @return
 */
func (dao CommonDao) GroupByFieldAndCount(entity dbinfo.Entity, sCreator string, fields map[string]string, currentUser string, onlyCreator bool) *emity.MsgEmity {
	return dao.GroupByFieldBase(entity, sCreator, fields, currentUser, onlyCreator, true)
}

/**
 * 根据字段名取分组数据
 * @param entity 实体类
 * @param sCreator 指定用户
 * @param fields 字段名与别名对象
 * @param currentUser 当前用户
 * @param onlyCreator 用户查询限制(仅创建者可见)
 * @param isGroupCount 添加分组后是否添加'数量列'
 * @return
 */
func (dao CommonDao) GroupByFieldBase(entity dbinfo.Entity, sCreator string, fields map[string]string, currentUser string, onlyCreator, isGroupCount bool) *emity.MsgEmity {
	if len(fields) < 1 {
		return emity.MsgEmity{}.Err(7001, "没有对应的待查字段！")
	}

	array := map[string]interface{}{}
	for key, value := range fields {
		array[key] = value
	}

	array = reflectutil.HoldByEntity(entity, array, "", "G") //按实体保留map中的数据

	tableInfo := entity.TableInfo()

	var build strings.Builder
	build.WriteString("SELECT @@")

	for key, val := range array {
		build.WriteString(",")
		build.WriteString(key)

		if val.(string) != "" {
			build.WriteString(" AS ")
			build.WriteString(val.(string))
		}
	}

	if isGroupCount {
		build.WriteString(",")
		build.WriteString(" COUNT(1) AS iCount")
	}

	build.WriteString(" FROM ")
	build.WriteString(gorm.GetDbName(tableInfo.GsDbName))
	build.WriteString(tableInfo.GsTableName)
	build.WriteString(" WHERE 1=1")

	if sCreator != "" {
		build.WriteString(" AND ")
		build.WriteString(globalconst.TableCreatorName)
		build.WriteString("=@sCreator")
	}

	where := map[string]interface{}{}
	if onlyCreator && (currentUser != "") {
		build.WriteString(" AND ")
		build.WriteString(globalconst.TableCreatorName)
		build.WriteString("=@sCreator")
		where["sCreator"] = currentUser
	}

	if tableInfo.GbHasDelSign { //存在逻辑删除字段
		build.WriteString(" AND ")
		build.WriteString(globalconst.TableDelSignName)
		build.WriteString(" != 1")
	}

	build.WriteString(" GROUP BY @@")

	for key := range fields {
		build.WriteString(",")
		build.WriteString(key)
	}

	sql := build.String()
	sql = strings.Replace(sql, " WHERE 1=1 GROUP BY ", " GROUP BY ", -1)
	sql = strings.Replace(sql, " @@,", " ", -1)
	sql = strings.Replace(sql, " 1=1 AND ", " ", -1)

	rows, err := gorm.Raw(sql, where).Rows()
	if err != nil {
		Log.Error("查询发生异常:", err)
		return emity.MsgEmity{}.Err(7003, "查询发生异常:", err)
	}
	defer rows.Close()

	res := gorm.ScanRows2mapI(rows)
	if res == nil {
		Log.Error("查询后数据转换发生异常:", err)
		return emity.MsgEmity{}.Err(7004, "查询后数据转换发生异常:", err)
	}

	if len(res) < 1 {
		return emity.MsgEmity{}.Err(7005, "数据不存在！")
	}

	return emity.MsgEmity{}.Success(res, "查询成功")
}

/**
 * 取表中指定字段的最大值
 * @param entity 实体类
 * @param sCreator 指定用户
 * @param field 字段名
 * @param where 查询条件
 * @param currentUser 当前用户
 * @param onlyCreator 用户查询限制(仅创建者可见)
 * @return emity.MsgEmity
 */
func (dao CommonDao) MaxByField(entity dbinfo.Entity, sCreator string, field string, whereInfo []dbinfo.WhereInfo, currentUser string, onlyCreator bool) *emity.MsgEmity {
	field = strings.TrimSpace(field)
	if field == "" {
		return emity.MsgEmity{}.Err(7001, "没有待查字段！")
	}

	whereInfo = holdByEntityToWhereInfo(entity, whereInfo) //按实体保留条件
	if len(whereInfo) < 1 {
		return emity.MsgEmity{}.Err(7002, "没有对应的查询条件！")
	}

	if !entity.HasColumnNames(entity, field) {
		return emity.MsgEmity{}.Err(7003, "指定字段不存在！")
	}

	tableInfo := entity.TableInfo()

	var build strings.Builder
	build.WriteString("SELECT MAX(")
	build.WriteString(field)
	build.WriteString(") AS data FROM ")
	build.WriteString(gorm.GetDbName(tableInfo.GsDbName))
	build.WriteString(tableInfo.GsTableName)
	build.WriteString(" WHERE 1=1")

	where := map[string]interface{}{}
	for _, value := range whereInfo {
		condition := value.Condition
		if condition == "" {
			condition = "="
		}

		build.WriteString(" AND ")
		build.WriteString(value.Name)
		build.WriteString(" ")
		build.WriteString(condition)

		if value.ValueName != "" {
			build.WriteString(" ")
			build.WriteString(value.ValueName)
			continue
		}

		build.WriteString(" @")
		build.WriteString(value.Name)
		where[value.Name] = value.Value
	}

	if sCreator == "" {
		build.WriteString(" AND ")
		build.WriteString(globalconst.TableCreatorName)
		build.WriteString("=@sCreator")
	}

	if onlyCreator && (currentUser != "") {
		build.WriteString(" AND ")
		build.WriteString(globalconst.TableCreatorName)
		build.WriteString("=@sCreator")
		where["sCreator"] = currentUser
	}

	if tableInfo.GbHasDelSign { //存在逻辑删除字段
		build.WriteString(" AND ")
		build.WriteString(globalconst.TableDelSignName)
		build.WriteString(" != 1")
	}

	sql := strings.Replace(build.String(), " 1=1 AND ", " ", 1)

	rows, err := gorm.Raw(sql, where).Rows()
	if err != nil {
		Log.Error("查询发生异常:", err)
		return emity.MsgEmity{}.Err(7004, "查询发生异常:", err)
	}
	defer rows.Close()

	res := gorm.ScanRows2mapI(rows)
	if res == nil {
		Log.Error("查询后数据转换发生异常:", err)
		return emity.MsgEmity{}.Err(7005, "查询后数据转换发生异常:", err)
	}

	if len(res) < 1 {
		return emity.MsgEmity{}.Err(7006, "数据不存在！")
	}

	return emity.MsgEmity{}.Success(res[0]["data"], "查询成功")
}

/**
 * 取表中指定字段的最小值
 * @param entity 实体类
 * @param sCreator 指定用户
 * @param field 字段名
 * @param where 查询条件
 * @param currentUser 当前用户
 * @param onlyCreator 用户查询限制(仅创建者可见)
 * @param whereStr 查询条件字符串
 * @return
 */
func (dao CommonDao) MinByField(entity dbinfo.Entity, sCreator string, field string, whereInfo []dbinfo.WhereInfo, currentUser string, onlyCreator bool) *emity.MsgEmity {
	field = strings.TrimSpace(field)
	if field == "" {
		return emity.MsgEmity{}.Err(7001, "没有待查字段！")
	}

	whereInfo = holdByEntityToWhereInfo(entity, whereInfo) //按实体保留条件
	if len(whereInfo) < 1 {
		return emity.MsgEmity{}.Err(7002, "没有对应的查询条件！")
	}

	if !entity.HasColumnNames(entity, field) {
		return emity.MsgEmity{}.Err(7003, "指定字段不存在！")
	}

	tableInfo := entity.TableInfo()

	var build strings.Builder
	build.WriteString("SELECT MIN(")
	build.WriteString(field)
	build.WriteString(") AS data FROM ")
	build.WriteString(gorm.GetDbName(tableInfo.GsDbName))
	build.WriteString(tableInfo.GsTableName)
	build.WriteString(" WHERE 1=1")

	where := map[string]interface{}{}
	for _, value := range whereInfo {
		condition := value.Condition
		if condition == "" {
			condition = "="
		}

		build.WriteString(" AND ")
		build.WriteString(value.Name)
		build.WriteString(" ")
		build.WriteString(condition)

		if value.ValueName != "" {
			build.WriteString(" ")
			build.WriteString(value.ValueName)
			continue
		}

		build.WriteString(" @")
		build.WriteString(value.Name)
		where[value.Name] = value.Value
	}

	if sCreator == "" {
		build.WriteString(" AND ")
		build.WriteString(globalconst.TableCreatorName)
		build.WriteString("=@sCreator")
	}

	if onlyCreator && (currentUser != "") {
		build.WriteString(" AND ")
		build.WriteString(globalconst.TableCreatorName)
		build.WriteString("=@sCreator")
		where["sCreator"] = currentUser
	}

	if tableInfo.GbHasDelSign { //存在逻辑删除字段
		build.WriteString(" AND ")
		build.WriteString(globalconst.TableDelSignName)
		build.WriteString(" != 1")
	}

	sql := strings.Replace(build.String(), " 1=1 AND ", " ", 1)

	rows, err := gorm.Raw(sql, where).Rows()
	if err != nil {
		Log.Error("查询发生异常:", err)
		return emity.MsgEmity{}.Err(7004, "查询发生异常:", err)
	}
	defer rows.Close()

	res := gorm.ScanRows2mapI(rows)
	if res == nil {
		Log.Error("查询后数据转换发生异常:", err)
		return emity.MsgEmity{}.Err(7005, "查询后数据转换发生异常:", err)
	}

	if len(res) < 1 {
		return emity.MsgEmity{}.Err(7006, "数据不存在！")
	}

	return emity.MsgEmity{}.Success(res[0]["data"], "查询成功")
}

/**
 * 检查关键值记录是否存在(返回1:存在;0:不存在)
 * @param entity 实体类
 * @param id 记录编号
 * @return emity.MsgEmity
 */
func (dao CommonDao) HasById(entity dbinfo.Entity, id interface{}) *emity.MsgEmity {
	if fmt.Sprintf("%v", id) == "" {
		return emity.MsgEmity{}.Err(7001, "记录编号参数为空！")
	}

	tableInfo := entity.TableInfo()

	var build strings.Builder
	build.WriteString("SELECT COUNT(1) AS iCount FROM ")
	build.WriteString(gorm.GetDbName(tableInfo.GsDbName))
	build.WriteString(tableInfo.GsTableName)
	build.WriteString(" WHERE ")
	build.WriteString(tableInfo.GsKeyName)
	build.WriteString(" =@")
	build.WriteString(tableInfo.GsKeyName)

	if tableInfo.GbHasDelSign { //存在逻辑删除字段
		build.WriteString(" AND ")
		build.WriteString(globalconst.TableDelSignName)
		build.WriteString(" != 1")
	}

	where := map[string]interface{}{tableInfo.GsKeyName: id}

	var iCount int
	dbResult := gorm.Raw(build.String(), where).Find(&iCount)
	if dbResult.Error != nil {
		Log.Error("查询发生异常:", dbResult.Error)
		return emity.MsgEmity{}.Err(7003, "查询数据发生异常:", dbResult.Error)
	}

	if iCount == 0 {
		return emity.MsgEmity{}.Err(0, "数据不存在！")
	}

	return emity.MsgEmity{}.Success(1, "数据存在！")
}

/**
 * 检查关键值记录是否存在(返回1:存在;0:不存在)
 * @param entity 实体类
 * @Param keyName 字段名
 * @Param keyValue 字段值
 * @return emity.MsgEmity
 */
func (dao CommonDao) HasByKey(entity dbinfo.Entity, keyName string, keyValue interface{}) *emity.MsgEmity {
	keyName = strings.TrimSpace(keyName)
	if keyName == "" {
		return emity.MsgEmity{}.Err(7001, "字段名参数为空！")
	}

	if (keyValue == nil) || (fmt.Sprintf("%v", keyValue) == "") || (fmt.Sprintf("%v", keyValue) == "<nil>") {
		return emity.MsgEmity{}.Err(7002, "字段值参数为空！")
	}

	if !entity.HasColumnNames(entity, keyName) {
		return emity.MsgEmity{}.Err(7003, "指定字段不存在！")
	}

	dataInfo := dbinfo.DataInfo{}.GetDataInfoByName(entity, keyName)
	if nil == dataInfo {
		return emity.MsgEmity{}.Err(7004, "字段备注信息缺失")
	}

	switch dataInfo.GsDbFileType {
	case "int":
		temp, err := strconv.Atoi(keyValue.(string))
		if err != nil {
			return emity.MsgEmity{}.Err(7005, "字段值参数为不符合规范！")
		}
		keyValue = temp
	case "bigint":
		temp, err := strconv.ParseInt(keyValue.(string), 10, 64)
		if err != nil {
			return emity.MsgEmity{}.Err(7006, "字段值参数为不符合规范！")
		}
		keyValue = temp
	}

	tableInfo := entity.TableInfo()

	var build strings.Builder
	build.WriteString("SELECT COUNT(1) AS iCount FROM ")
	build.WriteString(gorm.GetDbName(tableInfo.GsDbName))
	build.WriteString(tableInfo.GsTableName)
	build.WriteString(" WHERE ")
	build.WriteString(keyName)
	build.WriteString(" =@")
	build.WriteString(keyName)

	if tableInfo.GbHasDelSign { //存在逻辑删除字段
		build.WriteString(" AND ")
		build.WriteString(globalconst.TableDelSignName)
		build.WriteString(" != 1")
	}

	where := map[string]interface{}{keyName: keyValue}

	var iCount int
	dbResult := gorm.Raw(build.String(), where).Find(&iCount)
	if dbResult.Error != nil {
		Log.Error("查询发生异常:", dbResult.Error)
		return emity.MsgEmity{}.Err(7007, "查询数据发生异常:", dbResult.Error)
	}

	if iCount == 0 {
		return emity.MsgEmity{}.Err(0, "数据不存在！")
	}

	return emity.MsgEmity{}.Success(1, "数据存在！")
}

/**
 * 执行SQL脚本获取单行单列数据
 * 注意:库名必须用${}进行包装,此脚本应只存在一条记录且为单列
 * @param sql 待执行的SQL脚本
 * @param where 存放查询条件
 * @return emity.MsgEmity
 */
func (dao CommonDao) DoSql(sql string, where ...interface{}) *emity.MsgEmity {
	txt := gorm.ReplaceVariable(sql)

	var list []map[string]interface{}
	dbResult := gorm.Raw(txt, where...).Scan(&list)
	if dbResult.Error != nil {
		Log.Error("查询发生异常:", dbResult.Error)
		return emity.MsgEmity{}.Err(1002, "查询发生异常:", dbResult.Error)
	}

	if len(list) < 1 {
		return emity.MsgEmity{}.Err(1003, "查询成功但没有数据")
	}

	return emity.MsgEmity{}.Success(list, "查询成功")
}

/**
 * 执行SQL脚本获取单行单列数据
 * 注意:库名必须用${}进行包装,此脚本应只存在一条记录且为单列
 * @param sql 待执行的SQL脚本
 * @param where 存放查询条件
 * @return emity.MsgEmity
 */
func (dao CommonDao) ExecSql(sql string, where ...interface{}) *emity.MsgEmity {
	txt := gorm.ReplaceVariable(sql)

	dbResult := gorm.Exec(txt, where...)
	if dbResult.Error != nil {
		Log.Error("执行发生异常:", dbResult.Error)
		return emity.MsgEmity{}.Err(1001, "执行发生异常:", dbResult.Error)
	}

	if dbResult.RowsAffected < 1 {
		return emity.MsgEmity{}.Err(1002, "执行成功但没有影响数")
	}

	return emity.MsgEmity{}.Success(dbResult.RowsAffected, "执行成功")
}

/**
 * 执行SQL脚本获取单行单列数据
 * 注意:库名必须用${}进行包装,此脚本应只存在一条记录且为单列
 * @param sql 待执行的SQL脚本
 * @param where 存放查询条件
 * @return emity.MsgEmity
 */
func (dao CommonDao) GetValue(sql string, where ...interface{}) *emity.MsgEmity {
	txt := gorm.ReplaceVariable(sql)

	var list []map[string]interface{}
	dbResult := gorm.Raw(txt, where...).Scan(&list)
	if dbResult.Error != nil {
		Log.Error("查询发生异常:", dbResult.Error)
		return emity.MsgEmity{}.Err(1002, "查询发生异常:", dbResult.Error)
	}

	if len(list) < 1 {
		return emity.MsgEmity{}.Err(1003, "查询成功但没有数据")
	}

	var result interface{}
	row := list[0]
	for _, v := range row {
		result = v
	}

	return emity.MsgEmity{}.Success(result, "查询成功")
}

/**
 * 执行SQL脚本获取一行数据(多列)
 * 注意:库名必须用${}进行包装,此脚本应只存在一条记录
 * @param sql 待执行的SQL脚本
 * @param where 存放查询条件
 * @return emity.MsgEmity
 */
func (dao CommonDao) GetRow(sql string, where ...interface{}) *emity.MsgEmity {
	txt := gorm.ReplaceVariable(sql)

	var list []map[string]interface{}
	dbResult := gorm.Raw(txt, where...).Scan(&list)
	if dbResult.Error != nil {
		Log.Error("查询发生异常:", dbResult.Error)
		return emity.MsgEmity{}.Err(1001, "查询发生异常:", dbResult.Error)
	}

	if len(list) < 1 {
		return emity.MsgEmity{}.Err(1002, "查询成功但没有数据")
	}

	return emity.MsgEmity{}.Success(list[0], "查询成功")
}

/**
 * 执行SQL脚本获取多行数据(多列)
 * 注意:库名必须用${}进行包装,此脚本可返回多条记录
 * @param sql SQL脚本
 * @param where 存放查询条件
 * @return emity.MsgEmity
 */
func (dao CommonDao) GetRows(sql string, where ...interface{}) *emity.MsgEmity {
	txt := gorm.ReplaceVariable(sql)

	var list []map[string]interface{}
	dbResult := gorm.Raw(txt, where...).Scan(&list)
	if dbResult.Error != nil {
		Log.Error("查询发生异常:", dbResult.Error)
		return emity.MsgEmity{}.Err(1001, "查询发生异常:", dbResult.Error)
	}

	if len(list) < 1 {
		return emity.MsgEmity{}.Err(1002, "查询成功但没有数据")
	}

	return emity.MsgEmity{}.Success(list, "查询成功")
}

/**
 * 根据关键值翻转值(限布尔值类型,1转2,2转1)
 * @Param entity 实体类
 * @Param whereInfo 存放查询条件
 * @Param reversalColumn 翻转的字段名
 * @Param currentUser 当前用户
 * @Param onlyCreator 是否只翻转创建人创建的数据
 * @return emity.MsgEmity
 */
func (dao CommonDao) ReversalByKey(entity dbinfo.Entity, whereInfo []dbinfo.WhereInfo, reversalColumn, currentUser string, onlyCreator bool) *emity.MsgEmity {
	whereInfo = holdByEntityToWhereInfo(entity, whereInfo) //按实体保留条件
	if len(whereInfo) < 1 {
		return emity.MsgEmity{}.Err(7001, "没有对应的查询条件！")
	}

	tableInfo := entity.TableInfo()

	var build strings.Builder
	build.WriteString("UPDATE ")
	build.WriteString(gorm.GetDbName(tableInfo.GsDbName))
	build.WriteString(tableInfo.GsTableName)
	build.WriteString(" SET ")
	build.WriteString(reversalColumn)
	build.WriteString("= IF(")
	build.WriteString(reversalColumn)
	build.WriteString("=1,2,1)")
	build.WriteString(" WHERE 1=1")

	where := map[string]interface{}{}
	for _, value := range whereInfo {
		condition := value.Condition
		if condition == "" {
			condition = "="
		}

		build.WriteString(" AND ")
		build.WriteString(value.Name)
		build.WriteString(" ")
		build.WriteString(condition)

		if value.ValueName != "" {
			build.WriteString(" ")
			build.WriteString(value.ValueName)
			continue
		}

		build.WriteString(" @")
		build.WriteString(value.Name)
		where[value.Name] = value.Value
	}

	if onlyCreator && (currentUser != "") {
		build.WriteString(" AND ")
		build.WriteString(globalconst.TableCreatorName)
		build.WriteString("=@sCreator")
		where["sCreator"] = currentUser
	}

	if tableInfo.GbHasDelSign { //存在逻辑删除字段
		build.WriteString(" AND ")
		build.WriteString(globalconst.TableDelSignName)
		build.WriteString(" != 1")
	}

	sql := strings.Replace(build.String(), " 1=1 AND ", " ", 1)

	dbResult := gorm.Exec(sql, where)
	if dbResult.Error != nil {
		Log.Error("执行发生异常:", dbResult.Error)
		return emity.MsgEmity{}.Err(1001, "执行发生异常:", dbResult.Error)
	}

	if dbResult.RowsAffected < 1 {
		return emity.MsgEmity{}.Err(1002, "执行成功但没有影响数")
	}

	return emity.MsgEmity{}.Success(dbResult.RowsAffected, "执行成功")
}

/**
 * 根据条件仅查询指定字段名数据
 * @param entity 实体类
 * @param whereInfo
 * @param fieldNames 待取数据的字段名称集合
 * @Param currentUser 当前用户
 * @Param onlyCreator 是否只翻转创建人创建的数据
 * @return emity.MsgEmity 返回内容data中存放的是Map
 */
func (dao CommonDao) FindField(entity dbinfo.Entity, whereInfo []dbinfo.WhereInfo, fieldNames []string, currentUser string, onlyCreator bool) *emity.MsgEmity {
	fieldNames = holdByEntityToArray(entity, fieldNames) //按实体保留数组中的数据
	if len(fieldNames) < 1 {
		return emity.MsgEmity{}.Err(7001, "没有对应的数据可查询！")
	}

	whereInfo = holdByEntityToWhereInfo(entity, whereInfo) //按实体保留条件

	tableInfo := entity.TableInfo()

	var build strings.Builder
	build.WriteString("SELECT ")

	for _, val := range fieldNames {
		build.WriteString(",")
		build.WriteString(val)
	}

	build.WriteString(" FROM ")
	build.WriteString(gorm.GetDbName(tableInfo.GsDbName))
	build.WriteString(tableInfo.GsTableName)
	build.WriteString(" WHERE 1=1")

	where := map[string]interface{}{}
	for _, value := range whereInfo {
		condition := value.Condition
		if condition == "" {
			condition = "="
		}

		build.WriteString(" AND ")
		build.WriteString(value.Name)
		build.WriteString(" ")
		build.WriteString(condition)

		if value.ValueName != "" {
			build.WriteString(" ")
			build.WriteString(value.ValueName)
			continue
		}

		build.WriteString(" @")
		build.WriteString(value.Name)
		where[value.Name] = value.Value
	}

	if onlyCreator && (currentUser != "") {
		build.WriteString(" AND ")
		build.WriteString(globalconst.TableCreatorName)
		build.WriteString("=@sCreator")
		where["sCreator"] = currentUser
	}

	sql := strings.Replace(build.String(), ",", "", 1)
	sql = strings.Replace(sql, " WHERE 1=1 AND ", " WHERE ", -1)
	sql = strings.Replace(sql, " WHERE 1=1", " ", -1)

	rows, err := gorm.Raw(sql, where).Rows()
	if nil != err {
		Log.Error("查询发生异常:", err)
		return emity.MsgEmity{}.Err(7002, "查询发生异常:", err)
	}
	defer rows.Close()

	res := gorm.ScanRows2mapI(rows)
	if res == nil {
		Log.Error("查询发生异常:", err)
		return emity.MsgEmity{}.Err(7003, "查询发生异常:", err)
	}

	if len(res) < 1 {
		return emity.MsgEmity{}.Err(7004, "数据不存在！")
	}

	return emity.MsgEmity{}.Success(res, "查询成功")
}

/**
 * 按实体保留切片中的数据
 * object 待检查对象
 * whereInfo 数据
 */
func holdByEntityToWhereInfo(entity dbinfo.Entity, whereInfo []dbinfo.WhereInfo) []dbinfo.WhereInfo {
	columns := "," + entity.BaseColumnNames() + ","
	result := []dbinfo.WhereInfo{}
	for _, val := range whereInfo {
		if !strings.Contains(columns, ","+val.Name+",") {
			continue
		}

		result = append(result, val)
	}

	return result
}

/**
 * 按实体保留切片中的数据
 * object 待检查对象
 * data 数据
 * fieldPrefix 字段前缀(可不传)
 */
func holdByEntityToArray(entity dbinfo.Entity, data []string) []string {
	columns := "," + entity.BaseColumnNames() + ","
	result := []string{}
	for _, val := range data {
		if !strings.Contains(columns, ","+val+",") {
			continue
		}

		result = append(result, val)
	}

	return result
}
